I am working on migrating an application that manually writes script tags to one that uses the YUI3 loader to manage script dependencies. I'm running into an issue with scripts like jQuery that shouldn't be loaded twice, because in some cases legacy code drops the script on the page, and then the YUI loader later loads it up again. Is there a way to prevent this from happening? It seems like the loader should be able to query for script tags with the same src as the one it's going to create before injecting a new tag.
It turns out that one way to do this is to call Y.add() proactively on the module name. This works well for modules that are not themselves defined with Y.add() (e. g. jQuery plugins). However, there is a potential race condition if you do this with modules that ARE defined with Y.add(). For example, consider the following sequence:
The fix is to use the following script:
var preloadedModules = ['a', ... ]; // list of module scripts already on the page
, noop = function (Y) { }, version = '@VERSION@', i, len, moduleName;
for (var i = 0, len = preloadedModules.length; i < len; ++i) {
moduleName = preloadedModules[i];
if (!YUI.Env.mods[moduleName]) { // avoids overwriting YUI module definitions
YUI.add(moduleName, noop, version);
}
}