Loading a new version of jQuery without breaking an old version

Sometimes you’re working on a website that already uses an old version of jQuery and upgrading is not an option at that moment in time; if for example the jQuery library is bundled with a version of Drupal and works with a set of existing plugins.

The following code will allow you to load in a newer version of jQuery and still leave the $ variable assigned to the old version…

The code:

<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'> 
//<![CDATA[
google.load('jquery', '1.7.1'); 
//]]> 
</script>
<script type="text/javascript"> 
// save the new version of jquery to a variable and revert $ to the existing version on the page
var jQuery_1_7_1 = $.noConflict(false); 
</script>

The same code with console logging for testing:

<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
// outputs jquery version to Firebug/chrome console to test
console.log("$=" + $().jquery);
//<![CDATA[
google.load('jquery', '1.7.1');
//]]>
</script>
<script type="text/javascript">
console.log("$=" + $().jquery);
// save the new version of jquery to a variable and revert $ to the existing version on the page
var jQuery_1_7_1 = $.noConflict(false);
console.log("$=" + $().jquery);
console.log("jQuery_1_7_1=" + jQuery_1_7_1().jquery);
</script>

After that, you can use jQuery_1_7_1 in place of $ in your newer code.

Hat-tip to the following helpful articles:

One thought on “Loading a new version of jQuery without breaking an old version”

Comments are closed.