Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading Multiple jQuery Versions

I've written a tool that uses jQuery, and the tool is dynamically loaded on many different web pages, including ones that already use jQuery. I am trying to load jQuery on a web page that is out of my direct control. When I do so, Ajax calls that this page makes via jQuery stop working. The site, dailycaller.com, uses jQuery lazy image loading - when you scroll down the page, article images are dynamically loaded. When I attempt to load any jQuery version, this dynamic image fetching breaks. I suspect this is due to a version conflict between my loaded jQuery and the jQuery already on the page itself.

To test this, I tried loading the same version as the page does. The page includes a script tag

<script type='text/javascript' src='http://cdn01.dailycaller.com/wp-includes/js/jquery/jquery.js?ver=1.7.2'></script>

My JS code loads this version again (asynchronously, after the pageload), with

var script = document.createElement( 'script' );
script.src = 'http://cdn01.dailycaller.com/wp-includes/js/jquery/jquery.js?ver=1.7.2';
document.body.appendChild(script);

Even though this version of jQuery is, in theory, already on the page, this load causes the page's jQuery Ajax calls to break. How can I load an arbitrary jQuery version without breaking this page's dynamic loads?

I have tried using jQuery.noConflict() as recommended here Can I use multiple versions of jQuery on the same page? and it doesn't solve this issue.

like image 786
Emmett Butler Avatar asked Dec 08 '22 17:12

Emmett Butler


1 Answers

You need to allow the dynamically loaded copy of jQuery to finish loading before calling .noConflict(). Use the onload event on <script>.

Demo: jsFiddle

Script:

var script = document.createElement( 'script' );
script.onload = function () {
    jQuery.noConflict( true ); //remove this and image load fails
};
script.src = 'http://cdn01.dailycaller.com/wp-includes/js/jquery/jquery.js?ver=1.7.2';
document.head.appendChild(script);
like image 86
ThinkingStiff Avatar answered Dec 11 '22 11:12

ThinkingStiff