1

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
});
Thinking Sites
  • 3,494
  • 17
  • 30
  • I've added a solution for your exact problem in another similar question. Check http://stackoverflow.com/a/27422370/80779 I don't know what is Stackoverflow's policy on duplicated answers, so I'm not copying to whole answer content to this question. – LordOfThePigs Dec 11 '14 at 12:13
  • possible duplicate of [requireJS optional dependency](http://stackoverflow.com/questions/14164610/requirejs-optional-dependency) – LordOfThePigs Dec 15 '14 at 09:51
  • That's an interesting solution. I like it. – Thinking Sites Dec 15 '14 at 20:36

1 Answers1

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?

kryger
  • 12,906
  • 8
  • 44
  • 65