How to Use Multiple Versions of JQuery at the Same Time

You may find yourself in the unfortunate situation of having an unsupported library that depends on some old version of JQuery and its features.

The problem is that they have deprecated a lot of features these past few years and if you want to upgrade your JQuery, you may find your old library no longer works.

In an ideal world, you would spend time to refactor the code so that the library is no longer in use. But that is not always a task that can happen in a timely fashion when you are under pressure to roll things out.

Luckily, there is a dark magic hack that you can do to include multiple versions of JQuery. I got this solution from this 2009 blog post.

Let us say my library has an if statement:

if ($.browser.msie)

This is a way of checking if the browser is Internet Explorer. $.browser was removed in JQuery 1.9 and so if you tried to upgrade to that or later (say from version 1.6) it would fail and give you an error saying something like "browser is not a thing".

If you include both versions of JQuery:

<script src='//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>
<script src='//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

The last one loaded would be the JQuery that is used. In this case 3.1.1. But you can do the following:

<script src='//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>

<script type="text/javascript">
    var jQuery_old = $.noConflict(true);
</script>

<script src='//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

The middle script basically assigns jQuery_old to be version 1.6.2.

So if you use jQuery or $ you would be using the last loaded version, but if you use jQuery_old (or what ever you call the variable), you use the version you loaded before running $.noConflict.

This means you can change the earlier $.browser to:

if (jQuery_old.browse.msie)

Which would solve the non-existent function error.

As I said, I think that is a bit of a hack and I would only recommend is as a "temporary" solution (although we all know what happens to those). The correct way would be to upgrade to library (either yourself or if its still supported, see if there is is a more compatible version) or remove it completely.


© 2012-2017