imagine the following setup: A page that has an old jQuery version (say 1.5.2) - that I have no control over - loads a Javascript file from my servers that also need jQuery, but a more recent version. (for example 1.8.3) Now my script tries to do the following:
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js");
script.onreadystatechange = function() { // IE
if (script.readyState === "complete" || script.readyState === "loaded") {
ready();
}
};
script.onload = function() { // other browsers
ready();
};
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
The ready
function then checks if $
has the correct version of jQuery and if it does, it binds that jQuery instance to another variable and returns $
to the original jQuery version, via newjQuery = window.jQuery.noConflict(true);
.
Now this works all fine and dandy and there is no (outside) code execution happening between loading "my" jQuery version and restoring $ to "their" jQuery version - at least on Chrome, Firefox, etc. Where this approach fails is Internet Explorer, which for some reason processes at least 1 more "tick" of Javascript code that might be running in parallel. This tends to mess up code that is not compatible with "my" jQuery version and happens to get executed in the 5ms where IE has not executed the ready event yet.
Here's an example fiddle: http://jsfiddle.net/w5pPp/3/
In the fiddle, I test for the currently bound jQuery version every 10ms. Only in IE9 there sometimes is a short time span where $
refers to "my" jQuery, as indicated by a "THIS SHOULD NOT HAPPEN" log.
Now my question is this: What would be the best solution to load "my" jQuery version into its own variable without causing any problems in the execution of the page code in the short time span where it overwrites "their" jQuery before calling noConflict?