问题
Is there any way to have requireJS optionally (like maybe through a plugin) return null for a dependency that failed with a 404?
For example:
require(["allow404!myscript"], function(myscript){
console.info(myscript); // myscript should be null if myscript doesn't exist
});
回答1:
You could abuse paths config fallbacks to achieve this:
require(["myModuleOrNull"], function(myModuleOrNull) {
console.log(myModuleOrNull);
});
in your requirejs config:
paths: {
'myModuleOrNull': [
'unreliable-module-location',
// If above fails (timeout, 404, etc.) use the one below
'null-module'
]
}
and the null-module.js:
define([], function() {
return null;
});
...but why would you want to do that? Handling optional null where a module is expected will be nothing but pain. Is there some specific reason for doing this?
来源:https://stackoverflow.com/questions/15751642/null-dependencies-in-requirejs-when-ajax-returns-a-404