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