Handling prerequsites load failure in RequireJS require function

给你一囗甜甜゛ 提交于 2019-12-10 14:58:23

问题


I'm using RequireJS for AMD. Using this code I execute my function after ensuring the module1 is loaded:

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

In some cases the module1 is not available (mostly because of access security). I want to handle what happens if module1 failed to load. Using some code like:

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

or maybe the require function accepts another parameter for module load failures?

So the question is, how can I handle if the required module failed to load?


回答1:


See RequireJS API document: 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.
    }
});


来源:https://stackoverflow.com/questions/19343188/handling-prerequsites-load-failure-in-requirejs-require-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!