Is it possible to determine if a script is loading as a RequireJS module?

I am exploring if there is a way to determine if a given script is currently loading RequireJS. The answer for AMD modules in general will be even better, but my use case is only RequireJS.

jQuery and other libraries "discover" this:

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

In most cases, this is enough, but the problem is that it does not detect if the script is loading as an AMD module, it only determines if define exists and supports the AMD specification.

Is there a way, both with RequireJS and with AMD modules in general, for a script to determine (for real) whether it loads as a module?

+7
javascript requirejs amd
source share
1 answer

Check out the specified () :

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

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

Now the problem is how to get the module name, as it may vary depending on the user’s settings. There is a special module for this , but this only works if you are already in the define call. I recommend you contact jrburke , who is the developer of Requirejs.

+4
source share

All Articles