一个常见的应用场景是先用库的一个CDN版本,如果其加载出错,则切换到本地版本:
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 jQuerydoes 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.undef()”,如果你配置到不同的位置并重新尝试加载同一模块,则loader会将依赖于该模块的那些模块记录下来并在该模块重新加载成功后去加载它们。
注意: errback仅适用于回调风格的require调用,而不是define()调用。define()仅用于声明模块。
§ 4.6.3 paths备错配置
上述模式(检错,undef()模块,修改paths,重加载)是一个常见的需求,因此有一个快捷设置方式。paths配置项允许数组值:
requirejs.config({ //To get timely, correct error triggers in IE, force a define/shim exports check. enforceDefine: true, paths: { jquery: [ 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min', //If the CDN location fails, load from this location 'lib/jquery' ] } }); //Later require(['jquery'], function ($) { });
上述代码先尝试加载CDN版本,如果出错,则退回到本地的lib/jquery.js。
注意: paths备错仅在模块ID精确匹配时工作。这不同于常规的paths配置,常规配置可匹配模块ID的任意前缀部分。备错主要用于非常的错误恢复,而不是常规的path查找解析,因为那在浏览器中是低效的。
§ 4.6.4 全局 requirejs.onError
为了捕获在局域的errback中未捕获的异常,你可以重载requirejs.onError():
requirejs.onError = function (err) { console.log(err.requireType); if (err.requireType === 'timeout') { console.log('modules: ' + err.requireModules); } throw err; };