jQuery - Avoid conflicts with other libraries

  5 / 5 (1 Votes)
We are often encounter the problem of incompatibility between javascript libraries at create our website.

jQuery developers have thought of this and therefore have included in your library the noConflict() function to help us to solve the incompatibility of jQuery with other libraries or even with other versions of jQuery.

First of all, let's see how the noConflict() function works .
As we know, jQuery uses the $ symbol as a short form to avoid us use the word jQuery.
Once the jQuery library is loaded, it creates an internal variable called _$ establishing the value that already existed in the variable $ (If any) before setting it as its variable ($ = jQuery).
Likewise, the same is done with jQuery variable that is loaded into _jQuery.

When we use the noConflict() function, the variable $ reverts to the value it had previously to load our library jQuery and if we pass that function the value true will do the same with the jQuery variable.
The function returns the current jQuery object before overwriting the previous value.

Here's an example for better understanding. <script type="text/javascript">
    // We set the jQuery object and $ with our variables, in this case simple strings.
    var jQuery    = 'My object';
    var $        = 'My short object';

<!-- We load the jQuery library, at this point, jQuery and $ variables are overwritten and no longer have our strings. -->
<script type="text/javascript" src="jquery.min.js"></script>

<script type="text/javascript">
    /* All the jQuery library is loaded into jQuery2 and jQuery and $ variables again have the strings we set at the beginning.*/
    jQuery2 = jQuery.noConflict(true);
    // From here we can use the jQuery2 object
    jQuery2(function() {
        jQuery2('body').append('Body text string');
    // Alert message with the text "My object"

It is possible to use the variable $ within our jQuery2 object by a parameter in function.
For example: <script type="text/javascript">
    jQuery2(function($) {
        $('body').append('Body text string');

Here's an example using two versions of jQuery on the same file. <script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
    // We spent the jQuery object to jQuery190 and leave empty the jQuery object and $ to load the next library.
    jQuery190 = jQuery.noConflict(true);

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    // We spent the jQuery object to jQuery191 and leave empty jQuery and $.
    jQuery191 = jQuery.noConflict(true);

<script type="text/javascript">
    //At this point we can use the two libraries individually

    jQuery190(function($) {
        $('body').append('Example with jQuery 1.9.0');
    jQuery191(function($) {
        $('body').append('Example with jQuery 1.9.1');


Write comment