Tho*_*s K 11 javascript jquery requirejs
我的应用程序使用require.js,我有一个随机的bug(50次重载时发生1次)Require.js在控制台中写入:
无法加载资源:服务器响应状态为404(未找到)
确实,require.js尝试从错误的目录中包含jquery ...我不知道为什么,大多数时候应用程序工作正常...
我的配置非常简单:
require.config({
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
animate_from_to: {
deps: ['jquery']
},
bootstrap: {
deps: ['jquery']
},
zoom: {
deps: ['jquery']
},
shop_util: {
deps: ['jquery']
},
pricer: {
deps: ['jquery']
},
filter: {
deps: ['jquery']
},
paginator: {
deps: ['jquery']
},
},
paths: {
bootstrap: 'lib/bootstrap',
jquery: 'lib/jquery-1.9.1',
zoom: 'lib/jquery.zoom.min',
animate_from_to: 'lib/jquery.animate_from_to-1.0.min',
backbone: 'lib/backbone.min',
underscore: 'lib/underscore.min',
text: 'lib/require-text',
shop_util: 'lib/shop_util',
pricer: 'lib/pricer',
filter: 'lib/filter',
paginator: 'lib/paginator',
}
});
Run Code Online (Sandbox Code Playgroud)
谢谢
exp*_*nit 20
除了数据主脚本(js/main.js)之外,您的应用程序似乎还有另一个入口点.即使它是同一页面中的后续脚本,也不能依赖于在下一个脚本运行之前完成的数据主脚本,因为它加载了异步属性.
<script data-main="js/main" src="js/lib/require.js"></script>
<!-- foo.js might run before js/main.js !!! -->
<script src="js/foo.js"></script>
Run Code Online (Sandbox Code Playgroud)
您可以通过在js/main.js末尾添加一个console.log语句,在foo.js(或其他)中添加一个来证明这一点.通常你会看到来自js/main.js然后是foo.js的那个,但是在50个案例中你会看到它们以其他顺序发生.
有几种策略可以解决这个问题:
1 - 从您的数据主脚本中完成所有应用程序启动和后续要求
当然适用于单页应用程序.所有在一个文件:
require.config({
// snip
});
require(['mymodule'], function( mymodule ) {
// do stuff
});
Run Code Online (Sandbox Code Playgroud)
2 - 在require.js脚本标记后面使用内联脚本
而不是将上述脚本放在data-main引用的单独文件中,只需在下面有第二个脚本标记.这是文档中列出的第一个示例.
主要适用于单页面应用
3 - 在require.js脚本标记之前将require config加载到全局变量中
文档中列出的第二个示例.
<script>
var require = {
paths: { // define them}
shim: { // define them }
};
</script>
<script src="scripts/require.js"></script>
Run Code Online (Sandbox Code Playgroud)
主要适用于单页面应用
4 - 嵌套您的require调用以首先加载配置
这最适用于多页面应用程序,并且是多页面垫片应用程序示例中推荐的应用程序
<script src="js/lib/require.js"></script>
<script>
//Load common code that includes config, then load the app
//logic for this page. Do the require calls here instead of
//a separate file so after a build there are only 2 HTTP
//requests instead of three.
require(['./js/common'], function (common) {
//js/common sets the baseUrl to be js/ so
//can just ask for 'app/main1' here instead
//of 'js/app/main1'
require(['app/main1']);
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7276 次 |
| 最近记录: |