Loading jQuery in .noConflict() mode with RequireJS

This year I worked on a project where a third party toolbar was conflicting with a site using RequireJS. The toolbar was using an older version of jQuery that was leaking its scope and overriding the site copy of jQuery.

While ideally, the third party would fix their toolbar, I was nonetheless tasked with seeing if the site itself could prevent the toolbar from interfering.

jQuery has a .noConflict() mode to pass your version of jQuery to another variable and then relinquish the global jQuery and $ variables to other libraries or another version of jQuery.

1
2
3
var j = jQuery.noConflict(true);
j( "div p" ).hide();

Doing the same in a RequireJS setup needs a couple more steps.

The official RequireJS site has documentation on doing so http://requirejs.org/docs/jquery.html#noConflictmap, though I could not get this method working. The setup I had success with was based on this article http://coderwall.com/p/6evdta.

The finished working solution can be viewed here http://github.com/rnsloan/jquery-noConflict-requirejs.

This is how the RequireJS configuration looks:

1
2
3
4
5
6
7
8
9
10
11
12
requirejs.config({
baseUrl: "js/lib",
paths: {
"jqueryInternal": ['//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min','jquery-2.0.2.min'],
"jqueryNoConflict": 'jquery.no-conflict',
"app": "../app"
}
//shim config does not work with optimizer if loading resources from a url (jQuery)
});
requirejs(["app/main"]);

The paths to three modules are set-up:

  • jqueryInternal - jQuery loaded normally.
  • jqueryNoConflict - takes the jQuery loaded above and sets it up to run in noConflict() mode
  • app - standard JavaScript file using jqueryNoConflict.

    Note: no module has the been given the name jquery. This is to avoid potential problems when multiple versions of jQuery are running.

The jqueryNoConflict module sets up jQuery .noConflict() mode:

1
2
3
4
5
6
7
8
9
define(
[
'jqueryInternal'
],
function () {
return jQuery.noConflict(true);
}
);

Finally, jQuery can now be used in other JavaScript files by using the jqueryNoConflict module:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require(
[
"jqueryNoConflict"
],
function (jQuery) {
(function ($) {
/*
* start using jQuery normally here
*/
var version = $().jquery;
$('#version').text(version);
})(jQuery);
}
);

The complete solution http://github.com/rnsloan/jquery-noConflict-requirejs demonstrates this working by loading a different version of jQuery with a standard script tag alongside the RequireJS version and shows them running independently of each other.