requirejs - 如何处理来自 Requirejs 的 404 错误

标签 requirejs durandal durandal-2.0

我目前正在尝试确定处理 Durandal 应用程序中不同错误的最佳方法。我正在测试的一种情况是所需的模块不存在,即

define(['dummy'], function (Dummy) { return {}; });

在哪里 dummy不存在。我已在 requirejs.config({...}) 正下方的 main.js 文件中添加了以下内容:

requirejs.onError = function (err) {
    console.log('Global error', err);
};

但从这里永远不会记录错误。 Durandals system.js 文件的控制台窗口中显示了 404 错误,并且还记录了错误消息:

Uncaught Error :无法加载路由模块(viewmodels/features/errorHandling/scriptNotFound/one)。详细信息:脚本错误:dummy

它看起来像 requirejs.onError函数永远没有机会被调用。我希望能够记录这些错误并通知用户有问题等。有人知道我会怎么做吗?

最佳答案

A common use case for this is to use a CDN-hosted version of a library, but if that fails, switch to loading the file locally:


requirejs.config({
    enforceDefine: true,
    paths: {
        jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min'
    }
});

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

http://requirejs.org/docs/api.html#errbacks

关于requirejs - 如何处理来自 Requirejs 的 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20887510/

相关文章:

javascript - 如何在 typescript 中导入对象而不触发智能感知?

asp.net-mvc - 使用 gulp-useref Durandal 和 ASP.NET MVC 进行捆绑和串联

javascript - 处理循环依赖

electron - 通过requirejs导入 Electron

Durandal:确定 View 当前是否处于事件状态(可能使用路由器)?

dom - Durandal 小工具 : Knockout "<!-- ko if: -->" anomaly

jquery - Twitter Typeahead、Knockout JS 和 Twitter Bootstrap 3 运行不佳

javascript - RequireJS 和 Mustache(或任何其他引擎): where to put templates

javascript - 在 dojo 代码中包含 javascript 函数

javascript - 实现自定义加载消息 DURANDAL