5

我正在为 AMD 使用 RequireJS。module1使用此代码,我在确保已加载后执行我的函数:

require(['module1'], function (module1) {
    if (module1) {
        // My function code...
    }
); 

在某些情况下module1不可用(主要是因为访问安全性)。我想处理如果module1加载失败会发生什么。使用一些代码,如:

require(['module1'], function (module1) {
    if (module1) {
        // My function code...
    }
)
.fail(function(message)
{
    console.log('error while loading module: ' + message);
}

或者 require 函数可能接受另一个参数来表示模块加载失败?

所以问题是,如果所需的模块无法加载,我该如何处理?

4

1 回答 1

7

请参阅 RequireJS API 文档:http ://requirejs.org/docs/api.html#errors 。

require(['jquery'], function ($) {
    //Do something with $ here
}, function (err) {
    //The errback, error callback
    //The error has a list of modules that failed
    var failedId = err.requireModules && err.requireModules[0];
    if (failedId === 'jquery') {
        //undef is function only on the global requirejs object.
        //Use it to clear internal knowledge of jQuery. Any modules
        //that were dependent on jQuery and in the middle of loading
        //will not be loaded yet, they will wait until a valid jQuery
        //does load.
        requirejs.undef(failedId);

        //Set the path to jQuery to local path
        requirejs.config({
            paths: {
                jquery: 'local/jquery'
            }
        });

        //Try again. Note that the above require callback
        //with the "Do something with $ here" comment will
        //be called if this new attempt to load jQuery succeeds.
        require(['jquery'], function () {});
    } else {
        //Some other error. Maybe show message to the user.
    }
});
于 2013-10-13T09:46:23.050 回答