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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With