Require.js bug random无法加载资源

时间:2013-06-10 14:17:31

标签: 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',
  }

});

谢谢

1 个答案:

答案 0 :(得分:20)

除了数据主脚本(js / main.js)之外,您的应用程序似乎还有另一个入口点。即使它是同一页面中的后续脚本,也不能依赖于在下一个脚本运行之前完成的数据主脚本since it's loaded with async attribute

<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>

你可以通过在js / main.js末尾添加一个console.log语句,在foo.js(或其他)中添加一个来证明这一点。通常你会看到来自js / main.js然后是foo.js的那个,但是在50个案例中你会看到它们以其他顺序发生。

有几种策略可以解决这个问题:

1 - 从您的数据主脚本中启动所有应用启动和后续要求

当然适用于单页应用。全部在一个文件中:

require.config({
  // snip
});
require(['mymodule'], function( mymodule ) {
  // do stuff
});

2 - 在require.js脚本标记后面使用内联脚本

不要将上述脚本放在data-main引用的单独文件中,而是在下面放置第二个脚本标记。这是第一个示例listed in the docs

主要适用于单页应用

3 - 在require.js脚本标记之前将require config加载到全局变量

第二个例子listed in the docs

<script>
    var require = {
        paths: { // define them}
        shim: { // define them }
    };
</script>
<script src="scripts/require.js"></script>

主要适用于单页应用

4 - 嵌入您的必需来电以首先加载配置

这最适合多页应用,是the multi-page shim app example

中推荐的应用
<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>

相关问题hereherehere