Scenario:
I have some JS code, I want to detect if jQuery exists in the DOM already, if not add it:
if (typeof jQuery != 'function') {
var sc = document.createElement('script');
sc.type = 'text/javascript';
sc.async = true;
sc.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js";
sc.onload = function() { App.getTrackers(); };
sc.onreadystatechange = function() { App.getTrackers(); };
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(sc, s);
}
else {
App.getTrackers();
}
App = {
getTrackers: function() {
$.ajax({url: "/ajax.php", success: function(data) { console.log(data) }});
}
}
The onload() is for FF+Webkit; onReadyStateChange() is for IE
The issue is with IE, I’m getting this error:
'$' is undefined
Yet! IE’s console returns the contents of ajax.php. So the jQuery function has been executed… somehow. Even though $ was undefined…
Does $ not yet exist? Has it yet to be compiled even though the script has been downloaded?
The ready state has other values than
complete, so the event will be triggered at different stages until the code is loaded and completed.Check what the state is in the event handler: