Is there a way to prevent the YUI3 loader from loading scripts that are already on the page?

StackOverflow https://stackoverflow.com/questions/19181538

  •  30-06-2022
  •  | 
  •  

Domanda

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.

È stato utile?

Soluzione 2

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:

  1. script for module A is run (calls Y.add('A', ...))
  2. YUI goes off to load the requirements for module A before running the callback
  3. Y.add('A') is called again with an empty callback (to notify YUI that the script file for A is on the page)
  4. YUI since the async load hasn't yet returned, YUI takes the empty callback as the definition of A

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);
    }
}

Altri suggerimenti

About 3 / 4ths of this video you'll see how to load external modules not written for YUI and notify the loader that it has been loaded so it doesn't try to do it twice. Basically, you monitor the onProgress event of the loader and when it fires, you call YUI.add() with the name you want to give the module which will then make the loader mark that module as loaded.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top