Loading newer versions of jQuery and jQuery UI (noConflict)

Here’s an interesting problem:

You have an ASP.NET Web Forms application which references jQuery 1.3.x and would require a lot of testing to upgrade to a newer version of jQuery. You’re adding functionality to this application, and you really want to use jQuery 1.5 or jQuery 1.6 going forward with new development. But…, jQuery 1.3.x is referenced in the master page. Also, you want to load jQuery UI 1.8.x targeting the newer version of jQuery.

You could create another master page, but this could become confusing to maintain multiple master pages which do nothing more than reference a different version of jQuery. You could use a JavaScript bootloader like RequireJS to load your dependencies:

// This snippet from http://requirejs.org/docs/jquery.html
require(["jquery", "jquery.alpha", "jquery.beta"], function($) {
    //the jquery.alpha.js and jquery.beta.js plugins have been loaded.
    $(function() {
        $('body').alpha().beta();
    });
});

Another Option

One solution which doesn’t require a paradigm shift in how you load JavaScript files, and which can be modified easily after upgrading the core, older version, is to use jQuery.noConflict() to maintain versions.

For example:

// master page references jQuery 1.3.2, Your templated page starts here:
<script src="jquery.1.6.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var $jQuery = jQuery.noConflict(true); // http://api.jquery.com/jQuery.noConflict/
jQuery = $jQuery; // forces the new jQuery into global

jQuery(function($) {
  $.getScript('jquery.ui.1.8.13', function() {
      // do your thing, e.g.
      $('#dialog').dialog();
  });
});
</script>

First, you have to force the old version of jQuery out of the global. Then, you set the global.

Here, I’m pulling the jQuery UI library after the dom has loaded and performing all ui-related processing after the file loads. This could slow things down in the long-run, but it’s slightly more maintainable. For instance, after upgrading the core jQuery in your master template, you can remove the script tag in this view. The rest of the code can remain the same, unless you’re also upgrading jQuery UI.

If you find yourself doing hacks like this very often, you should bite the bullet and upgrade the base and avoid the jQuery.noConflict() stuff in the first place.

Related Articles