【问题标题】:Handling prerequsites load failure in RequireJS require function处理 RequireJS require 函数中的先决条件加载失败
【发布时间】:2013-10-13 08:22:58
【问题描述】:

我正在为 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 函数可能接受另一个参数来表示模块加载失败?

那么问题来了,如果需要的模块加载失败,我该如何处理?

【问题讨论】:

    标签: javascript requirejs amd


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答,但它的格式存在一些问题,我已经更正了。
    • 实际上,对我来说,errback 函数从未被调用过。
    • 请记住,如果 require 配置为无限超时 (waitSeconds: 0),并且依赖项之一挂起,则永远不会调用 errorcallback。
    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多