You can load multiple versions of jQuery in a page using jQuery’s noConflict() method. Before we delve into how to do it let me give a quick explanation of how noConflict() works.

jQuery for it’s working, internally uses jQuery as the global variable. $ variable that most of us are familiar with is just an alias to the jQuery variable. When jQuery is initialized in a page, the first thing it does is copy the variables $ and jQuery(if another version of jQuery has already been loaded or $ is a variable already used by some other script in the page) into separate variables so that these two variables are not over written by the currently initialized jQuery. When noConflict is called, jQuery re assigns the backed up jQuery(if a boolean true is passed) and $ variables to jQuery and $ so that the values $ and jQuery held before the initialization of current jQuery are restored.

Also noConflict() method takes a boolean argument which instructs jQuery to reassign jQuery variable also to it’s previous value. If the boolean argument is not passed then only $ is re assigned to it’s previous value.

Now that we know how noConflict() works let us put it into use in the below scenario. Say that you are writing a JavaScript widget which will be hosted in a third party domain. Your script makes use of jQuery and you do not want to rely on the third party loading jQuery for your script to use. So you bundle up jQuery along with your widget code and ship it to the third party site. Now you might face a scenario in which jQuery might have already been loaded by the third party for their own use or once your widget is loaded the third party site might load their own jQuery script. In such scenarios you have to take care that their jQuery is not rendered moot because of you loading your own jQuery in your widget.

As soon as you load your own version of jQuery and before doing anything else call noConflict(true) and assign the returned value to a variable of your own. Make sure that the widget script uses the variable you just used for all references to jQuery.

//assign our jQuery to a new variable
var myOwnJQuery = $.noConflict(true);
//rest of the widget code that used jQuery will have to use myOwnJQuery as the jQuery variable instead of $ or jQuery
Advertisements