The jQuery core: Using jQuery with Other JavaScript Libraries

From time to time you may want to include in your program other JavaScript frameworks or libraries with your code. If those frameworks use the dollar sign as a variable, this will cause conflicts. But, because jQuery plays nice with others, it has a method for avoiding these conflicts. To do so, use the $.noConflict(); method after loading the libraries that may conflict. This has the effect of reverting the dollar sign to its previous value. After invoking .noConflict(), use jQuery instead of $ to refer to the jQuery core. The following code demonstrates an example:

<html>

<head>

<script src=”conflictingFramework.js”></script>

<script src=”jquery.js”></script>

<script>

jQuery.noConflict();

jQuery(“<p>I am a paragraph</p>”).appendTo(body);

// $ references conflictingFramework.js, not jQuery

$.blahMethodFromOtherLibrary();

</script>

</head>

<body>

</body>

</html>

Opening up the hood, you can see the actual definition of $.noConflict():

noConflict: function( deep ) {

window.$ = _$;

if ( deep ) {

window.jQuery = _jQuery;

}

return jQuery;

},

As you can see, it’s very short. jQuery maintains an internal reference to the value of $ — after $.noConflict is called, the value of $ is restored to its previous value, which is the value of the conflicting library.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *