Handling jQuery Component Collision

My suggestion would be to use a mix of code isolation in an anonymous function and checking if jquery is already present.

Here’s an example:

(function() {

var jQuery;  // your jquery variable

// check if jquery is present and if it has the version you want
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.8.3') {

    // load jquery lib from google hosted libraries
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js");

    // wait for jquery lib to load
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function () { // old versions of IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
              jqueryLoadHandler();
          }
      };
    } else { // for other browsers
      script_tag.onload = jqueryLoadHandler;
    }

    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);

} else {

    // The current site is already using the jquery you want, so just point your variable to that jquery
    jQuery = window.jQuery;
    main();
}

// as soons as jquery is loaded
function jqueryLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);

    // Call plugin main function
    main(); 
}

// plugin main function
function main() { 
    jQuery(document).ready(function($) { 
        // Here you can use the $ without any problems
    });
}

})(); // We call our anonymous function immediately

This way you can use jQuery without problems in your plugin, even if other plugins used jquery without wp_enqueue_script.
Every variables and functions you use inside this anonymous function won’t interfere with the rest of the page.

Maybe this could work even better if it was integrated with wp_enqueue_script.

You can read more about this approach of loading jquery inside an anonoymous function in http://alexmarandon.com/articles/web_widget_jquery/

Leave a Comment