Configuring jQuery Not to Conflict with Other Libraries - J Query

Problem
If jQuery is loaded on the same page as another JavaScript library, both libraries may have implemented the $ variable, which results in only one of those methods working correctly.

Solution

Let’s say you inherit a web page that you need to update, and the previous programmer used another JavaScript library like Prototype, but you still want to use jQuery. This will cause a conflict, and one of the two libraries will not work based on which library is listed last in the page head.
If we just declare both jQuery and Prototype on the same page like so:

this will cause a JavaScript error: element.dispatchEvent is not a function in prototype.js. Thankfully, jQuery provides a workaround with the jQuery.noConflict() method:

When you call jQuery.noConflict(), it gives control of the $ variable back to whomever implemented it first. Once you free up the $ variable, you only will be able to access jQuery with the jQueryvariable. For example, when you used to use $("div p"), you would now use jQuery("div p").

Discussion

The jQuery library and virtually all of its plugins are constrained by the jQuery namespace. You shouldn’t get a conflict with the jQuery variable and any other library (i.e., Prototype, YUI, etc.). jQuery does however use $ as a shortcut for thejQuery object. This shortcut definition is what conflicts with other libraries that also use the $ variable. As we’ve seen in the solution, we can free jQuery of the $ shortcut and revert to using the jQuery object.
There is another option. If you want to make sure jQuery won’t conflict with another library but still have the benefit of a short name, you can call jQuery.noConflict() and assign it to a variable:

You can define your own short name by choosing the variable name you assign,
jQuery.noConflict().
Finally, another option is to encapsulate your jQuery code inside a closure:
jQuery.noConflict();

By using a closure, you temporarily make the $ variable available to the jQuery object while being run inside the function. Once the function ends, the $ variable will revert to the library that had initial control.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics