在require.js和use.js中顺序加载脚本

时间:2012-06-19 07:47:43

标签: javascript requirejs

我在我的项目require.js中使用它的插件use.js。

require.config({
// Initialize the application with the main application file
deps: ["main"],

paths: {
    // JavaScript folders
    libs: "../assets/js/libs",
    plugins: "../assets/js/plugins",

    // Libraries
    jquery: "../assets/js/libs/jquery",
    underscore: "../assets/js/libs/underscore",
    backbone: "../assets/js/libs/backbone",
    jqueryUI: "../assets/js/libs/jqueryUI",
    jquerySlider: "../assets/js/libs/slider",
    jqueryMouseWheel: "../assets/js/libs/jquery.mousewheel",    
    jquerySelectBox: "../assets/js/libs/selectBox",
    jqueryMouse: "../assets/js/libs/mouse",
    bookReader: "../assets/js/libs/newReader",

    // Shim Plugin
    use: "../assets/js/plugins/use"
},

use: {
    backbone: {
        deps: ["use!underscore", "jquery"],
        attach: "Backbone"
    },

    underscore: {
        attach: "_"
    },

    jqueryUI: {
        deps: ["jquery"]
    },

    jquerySlider: {
        deps: ["jquery", "jqueryMouse"]
    },

    jquerySelectBox: {
        deps: ["jquery"]
    },

    jqueryMouse: {
        deps: ["jquery", "jqueryUI"]
    },

    jqueryMouseWheel: {
        deps: ["jquery", "jqueryUI"]
    },

    bookReader: {
        deps: ["jquery", "jqueryUI", "jqueryMouse", "jquerySlider", "jqueryMouseWheel", "jquerySelectBox"],
        attach: "Reader"
    }
}
});

问题是脚本同时开始加载,并且由于存在未满足的依赖关系,通常会出现这两个错误

Uncaught TypeError: Object function (a, b) {return new e.fn.init (a, b, h)} has no method 'widget': 4444/assets/js/libs/mouse.js: 15
Uncaught TypeError: Cannot read property 'mouse' of undefined: 4444/assets/js/libs/slider.js: 20

文件在缓存中后,问题不再出现。 所以,我的问题。如何指定脚本必须一致地加载?

可以构建将它们包装到一个文件中的脚本。但是这个选项不是很理想

谢谢!

1 个答案:

答案 0 :(得分:1)

看看这个名为STEP的AMD加载器插件,它允许您按顺序加载脚本。

https://github.com/requirejs/step