When using RequireJS, it is important to note that RequireJS only knows about what it loads itself. If a script loads jQuery through a script
element and then a RequireJS module tries to load the jquery
module again, RequireJS will attempt to load jQuery once more without checking if it has already been loaded with a script
element before RequireJS was initialized.
However, there is a way for you to handle this situation. You can write code to specifically deal with this scenario. For example, your RequireJS configuration could include logic to verify whether jQuery
is already defined:
if (typeof jQuery === 'undefined') {
require.config({
paths: {
jquery: ...path/to/a/cdn/or/a/local/copy...
}
});
}
else {
define('jquery', [], function () { return jQuery; });
}
In the above code snippet, the true
branch of the if
statement handles the case where jQuery has not yet been loaded and configures RequireJS to find it accordingly. On the other hand, the false
branch defines a jquery
module that simply returns the globally available jQuery
, preventing RequireJS from reloading jQuery unnecessarily.
A similar approach can be taken when testing for Angular. It is worth noting that `require.config` can be invoked multiple times, and RequireJS will merge the values provided in each call.