如何使用requirejs正确定义shim配置

时间:2013-11-20 15:17:09

标签: javascript jquery requirejs

我通过jQuery加载jQueryRequireJS插件。

这就是requirejs.config的样子:

requirejs.config({
baseUrl: "http://mysite.example.com",
"paths": {

    // libraries
    "jquery": "Static/js/library/jquery/jquery-1.10.2",
    "jquery_sortable" : "Static/js/library/jquery-sortable/jquery-sortable",

    shim: {
        'jquery_sortable': ['jquery']
    }
}
});

当我快速刷新页面两次或更多时,sometimes我在插件代码中得到一个异常:

Uncaught ReferenceError: jQuery is not defined

基本上,我的插件不使用我为其设置的shim

指定shim配置的最可靠方法是什么?

3 个答案:

答案 0 :(得分:3)

可能是因为你没有按预期进行构建。正如您所注意到的那样,shim放在paths内。可能是。

"paths": {

// libraries
"jquery": "Static/js/library/jquery/jquery-1.10.2",
"jquery_sortable" : "Static/js/library/jquery-sortable/jquery-sortable",

shim: {
    'jquery_sortable': ['jquery']
}

}

-------评论后编辑------

也许尝试定义手册中声明的dep?

'foo': {
    deps: ['bar'],
    ...

来源:http://requirejs.org/docs/api.html#config-shim

答案 1 :(得分:1)

这很奇怪,因为我在网上看到的所有例子都将shim配置放在requirejs.config的最后一位,但把它置于顶端似乎解决了我的问题。

requirejs.config({
    baseUrl: "http://mysite.example.com",
    shim: {
            'jquery_sortable': ['jquery']
        },
    "paths": {

        // libraries
        "jquery": "Static/js/library/jquery/jquery-1.10.2",
        "jquery_sortable" : "Static/js/library/jquery-sortable/jquery-sortable"

    }
});

答案 2 :(得分:0)

我觉得这是因为RequireJS异步加载脚本。出于性能原因,这会发生,即脚本将并行加载。对于普通的AMD模块,这是可以的; RequireJS将保留define(["deps"], function(){...})调用的依赖关系树,但将<{1}}推迟执行,直到其依赖关系得到解决。

然而,对于非AMD,shimmed模块(如jQuery-UI),整个脚本将在加载时执行。这意味着,如果有可能的话,可以排序&#34;在&#34; jquery&#34;之前加载,它将找到它的依赖关系并在你写的时候失败。

我认为唯一可靠的解决方法是在function()之后立即将jQuery包含为普通的<script>标记。这样您就无法使用require.js属性来加载切入点,您必须单独data-main

require
相关问题