How to isolate different javascript libraries on the same page?

sha1dy picture sha1dy · Nov 12, 2010 · Viewed 9.9k times · Source

Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it.

Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example.

What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?

Answer

lawnsea picture lawnsea · Nov 12, 2010

Actually, I think jQuery.noConflict is precisely what you want to use. If I understand its implementation correctly, your code should look like this:

(function () {
var my$;

// your copy of the minified jQuery source

my$ = jQuery.noConflict(true);
// your widget code, which should use my$ instead of $
}());

The call to noConflict will restore the global jQuery and $ objects to their former values.