Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 脚本加载顺序_Javascript_Requirejs - Fatal编程技术网

Javascript 脚本加载顺序

Javascript 脚本加载顺序,javascript,requirejs,Javascript,Requirejs,我正在使用RequireJS声明项目中需要的依赖项。我已经配置了RequireJS,以便加载jQuery。但是,由于某些原因,浏览器会给出未定义jQuery的错误(Bootstrap.js需要jQuery) 是因为requireJS异步加载依赖项,所以它实际上可能发生在bootstrap.js加载之后 if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery'

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


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

if (typeof jQuery === 'undefined') {
  throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
引导仅全局检查jQuery。当浏览器尝试加载引导时,jQuery可能还不存在,因为RequireJS异步加载模块

现在Bootstrap不会将自身导出为AMD模块。为了确保RequireJS能够加载引导以及在jQuery之后加载引导,您可以使用和配置
path
将模块名称映射到模块文件,而
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
作为其依赖项之一。

从html中删除
bootstrap.js
导入,并将其依赖项添加到
main.js
中,正如您提到的那样,requirejs异步加载依赖项,并且可能会在加载jquery之前加载bootstrap.js文件。尝试将bootstrap.js定义为requirejs中的依赖项。
require.config({path:{'bootstrapBlah':'../modules/bootstrap',
..'它做什么?我以为它只指定模块的路径,这样当我使用bootstrapBlah作为依赖项时,它就会知道在哪里可以找到它。显然,即使我没有在任何地方声明bootstrapBlah作为依赖项,它也会加载脚本。这在我的main.js文件中。@user5539357是的,忘记了路径。添加它。我只是问“路径”有什么作用,因为,正如我所说的,我最初认为它只让我指定模块位置,但显然它也会加载它。shim,如果我没有弄错的话,让我声明不符合AMD的模块的依赖关系(如本例)@user5539357不,
path
没有加载引导。它保存该位置,然后继续,然后当它找到
require(['…','bootstrap'),
时,它会想“好的,我需要引导。但是,有人告诉我,我不需要在根目录中查找,而需要在这里查找”。因此,如果您剪切了
main.js
,如果我没有弄错,它将不会加载引导。@Katana314是的。
路径
只告诉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'],
  },
}