4

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?

Vivek Pradhan
  • 4,361
  • 3
  • 21
  • 42
Ingo Just
  • 123
  • 2
  • 8

1 Answers1

3

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).

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 246,787
  • 79
  • 474
  • 476