Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to isolate different javascript libraries on the same page?

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?

like image 867
sha1dy Avatar asked Nov 12 '10 12:11

sha1dy


People also ask

Can I use JavaScript and jQuery on same page?

Projects In JavaScript & JQueryYes, you can use multiple versions of jQuery on the same page. To avoid any kind of conflict, use the jQuery. noConflict() method.

What is jQuery conflict?

jQuery - noConflict() Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all the functionality is available without using $. Run $. noConflict() method to give control of the $ variable back to whichever library first implemented it.


2 Answers

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.

like image 177
lawnsea Avatar answered Sep 20 '22 15:09

lawnsea


Function(...) makes an eval inside your function, it isn't any better.

Why not use the iframe they provide a default sandboxing for third party content.

And for friendly ones you can share text data, between them and your page, using parent.postMessage for modern browser or the window.name hack for the olders.

like image 45
Mic Avatar answered Sep 20 '22 15:09

Mic