I am writing a Javascript library that requires jQuery 1.7 or higher. However, users of my library could be loading their own version of jQuery on their websites, which we can't control. Right now, I am loading jQuery asynchronously with a callback in my library, and using jQuery's noConflict(true) method to deal with version conflicts.
I have not come across any issues so far, but problems relating to asynchronous behavior and concurrency are random and very difficult to test. I am not very familiar with the details of asynchronous functions in Javascript, so I want an explanation. Let's say I have the following code:
Code on user's website:
// loading javascript library
<script type="text/javascript" src="library.js">
// loading jQuery version lower than 1.7.0
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js">
Code in library for loading jQuery asynchronously:
// set jQuery and $ to $j using noConflict()
loadScript("//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", function() {
$j = jQuery.noConflict(true);
});
function loadScript(url, callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
As I understand it, the user's page will first load my library's code, which will begin to load jQuery 1.11.1 asynchronously and use jQuery.noConflict(true)
to rename the jQuery and $ global variables. The page will then continue to load jQuery 1.2.3 on the original page. So jQuery and $ should refer to 1.2.3, while $j will refer to 1.11.1.
However, is it possible for $j to ever point to 1.2.3 instead of 1.11.1 due to the asynchronous loading of jQuery or multithreading in browsers? For example, can the line that loads jQuery 1.2.3 be executed right before $j = jQuery.noConflict(true)
, so that $j would now point to jQuery 1.2.3 (the current version of jQuery)? If so, what are some ways to resolve this issue? Thanks!