我正在使用RequireJS for AMD。使用此代码,我确保加载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函数是否接受模块加载失败的另一个参数?
所以问题是,如果所需模块加载失败,我该如何处理呢?
答案 0 :(得分:7)
请参阅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.
}
});