在 RequireJS 中处理先决条件加载失败需要功能



我正在使用 RequireJS for AMD。使用此代码,我在确保加载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函数接受模块加载失败的另一个参数?

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

请参阅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.
    }
});

最新更新