RequireJS - Isolating jQuery versions and plugins within contexts

718 views Asked by At

I have a project which utilizes multiple require contexts and dynamically loaded jQuery versions and plugins. (The jQuery versions will be centrally sourced and will not be inlined). jQuery integrity for the host and each context as well as plugin isolation are critical.

I am writing a loader plugin for RequireJS to handle the following use cases:

  • Within a specific require context
  • And without affecting the fn of the hosting page or any other require context, I would like to:
    • Load any version of jQuery I need
    • Load plugins onto the fn of my specific jQuery version
    • Have referential integrity on a required jQuery version such that any module within my require context can share plugins

I have an example project for the loader with tests here.

It is failing on the last condition when I make a second call using the loader, it is blowing away the prior version.

I am also using eval to isolate the the $ references in the loaded plugins to the locally loaded jQuery version scope. Any thoughts on a better way to do this would be appreciated.

Want to Keep it Simple (Stupid) if there's an easier/cleaner solution.

Thanks, much.

1

There are 1 answers

0
Dave On

I've also had to do this in a plugin. You should check out http://api.jquery.com/jQuery.noConflict/. To give an example:

jQueryLocal = jQuery.noConflict(true);

But you should certainly try to avoid loading multiple jQueries. You could, for example, check if a sufficient version is already loaded (in my case, I checked if 1.9+ was available before loading anything, and if so set the local variable to a simple reference to the existing global jQuery object, but then I wasn't using plugins.

You can check the version with:

var jQueryLocal;
var versions = (jQuery && /^([0-9]+)\.([0-9]+)\./.exec( jQuery.fn.jquery )) || [0,0];
if( versions[0] > 1 || versions[1] >= 9 ) {
    jQueryLocal = jQuery;
} else {
    // load script with whatever you're doing. If it's asynchronous, set callbacks etc.
    jQueryLocal = jQuery.noConflict(true);
}