Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to detect if a script is being loaded as a RequireJS module?

I'm researching whether there is a way to detect, for sure, whether a given script is currently being loaded by RequireJS. An answer for AMD modules in general would be even better, but my use case is only RequireJS.

jQuery and other libraries "detect" it like so:

if ( typeof define === "function" && define.amd ) {
    define( "jquery", [], function() {
        return jQuery;
    });
}

That is sufficient in most cases, but the problem is that it doesn't detect whether the script is being loaded as an AMD module, it only detects whether define exists and supports the AMD spec.

Is there a way, either with RequireJS or with AMD modules in general, for a script to determine (for real) whether it is being loaded as a module?

like image 864
mwcz Avatar asked Aug 06 '13 15:08

mwcz


1 Answers

Take a look at specified():

parentRequire.specified(moduleName): Returns true if the module has already been requested or is in the process of loading and should be available at some point.

if (typeof require === "function" && typeof require.specified === "function" && require.specified("jquery")) {
    define("jquery", [], function () {
        return jQuery;
    });
}

Now the problematic thing is how to get the module name because it may differ depending on the user setup. There is a special module for that, but that works only if you are already in a define call. I recommend you contact jrburke who is the Requirejs developer.

like image 93
jgillich Avatar answered Oct 25 '22 23:10

jgillich