在RequireJS require函数中处理先决条件加载失败 [英] Handling prerequsites load failure in RequireJS require function

查看:437
本文介绍了在RequireJS require函数中处理先决条件加载失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AMD的RequireJS.使用此代码,在确保加载module1后执行我的功能:

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

在某些情况下,module1不可用(主要是由于访问安全性).我想处理如果module1加载失败的情况.使用一些代码,例如:

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);
}

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

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?

推荐答案

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

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

这篇关于在RequireJS require函数中处理先决条件加载失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆