Handling jQuery Component Collision

In plugin development, what is the best practice to prevent jQuery component collision on the front end?

For instance, let’s say I include the jQuery Apprise dialog in a plugin that loads this on the front-end for something, yet another plugin may do the same. Because this gets loaded and declared twice, or perhaps one is forked and customized while mine is not, we get Javascript errors on the frontend (I assume).

(Note that I’m doing the best practice of using the wp_register_script() and wp_enqueue_script() strategy via a wp_head() action event in order to load a jQuery component on the frontend.)

3 Answers
3

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