脚本加载顺序

时间:2016-01-04 19:19:30

标签: javascript requirejs

我使用RequireJS在项目中声明我需要的依赖项。我已经配置了RequireJS以便加载jQuery。但是,出于某种原因,浏览器会给出jQuery未定义的错误(Bootstrap.js需要jQuery)。

_to

是因为requireJS异步加载依赖项,所以它实际上可能在bootstrap.js加载后发生了吗?

1 个答案:

答案 0 :(得分:3)

if (typeof jQuery === 'undefined') {
  throw new Error('Bootstrap\'s JavaScript requires jQuery')
}

Bootstrap仅检查全局jQuery。当浏览器尝试加载Bootstrap时,jQuery可能还没有,因为RequireJS异步加载模块。

现在,Bootstrap不会将自身导出为AMD模块。为了确保RequireJS能够加载Bootstrap并确保它在jQuery之后加载,您可以使用pathsshim配置。 paths将模块名称映射到模块文件,而shim告诉RequireJS它的依赖项。

paths: {
  // We tell RequireJS that `bootstrap` module is this file
  bootstrap: 'path/to/bootstrap.js'
},
shim: {
  // We tell RequireJS that `bootstrap` will need `jquery` loaded first
  bootstrap: {
    deps: ['jquery'],
  },
}

然后在main.js中,加载bootstrap作为其依赖项之一。

相关问题