Ingo Just Ingo Just - 6 months ago 118
Javascript Question

IE9 - SCRIPT5009: "jQuery" is undefined

the following code runs into the error SCRIPT5009: "jQuery" is undefined in IE9 (maybe also in older IE versions):

var $tx;
if (window.jQuery) {
$tx = jQuery;
if( jQuery().jquery.replace(".", "") < 17.1 ) {
addjQuery();
}
} else {
addjQuery();
}
function addjQuery() {
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"><\/script>');
document.write('<script type="text/javascript">$tx = jQuery.noConflict();<\/script>');
}
document.write('<script src="workingScript.js"><\/script>');


I solved it! It's working fine this way:

var $tx;
if (window.jQuery) {
$tx = jQuery;
if( jQuery().jquery.replace(".", "") < 17.1 ) {
addjQuery();
}
} else {
addjQuery();
}
function addjQuery() {
loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js", function(){
$tx = jQuery.noConflict(true);
});
}
document.write('<script src="workingScript.js"><\/script>');

function loadScript(url, callback){

var script = document.createElement("script")
script.type = "text/javascript";

if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}


workingScript.js:

(function ($) {
// some code here
})($tx);


The error occours here "$tx = jQuery.noConflict();" if
addjQuery
function is called. If the website already uses the current jQuery version, erverythings works fine.

Does anyone have an idea how to solve this?

Answer

Your script loads other scripts during its execution, they won't execute synchronously but rather asynchronously. When $tx = jQuery.noConflict(); executes there is no guarantee the jQuery loaded.

If you need to do it synchronously see this question , or better yet use something like RequireJS that handles this for you. (It also allows that sort of fallback).