javascriptreadystateonreadystatechange

dynamically creating script: readyState never "complete"


I'm trying to do something AFTER a script is completely loaded. (IE8)

Script I use for testing: http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
and the invalid one: http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.minaaaaaaaa.js

The code...

var script = create the element and append to head...

// this works fine with FF/Chrome/...
script.onload = function() {alert('script loading complete');}
script.onerror = function() {alert('error loading script');}

// and for IE
script.onreadystatechange = function() {
    // this will alert 1.loading 2.loaded
    alert(this.readyState);

    // this never works
    if(this.readyState == 'complete') {alert('script loading complete');}

    // this works with either a valid or INVALID url
    else if(this.readyState == 'loaded') {alert('script loaded');}
};

In my case, the "complete" never shows, the "loaded" shows even if a url is invalid. So there's no way to tell if a script is CORRECTLY loaded UNDER IE.

Am I doing something wrong? How come I never get the complete state?

UPDATE

OK, I just read some articles and it seems that readystate is not a reliable way to detect script loading.

So is there another way to do so? without jQuery, but pure Javascript.


Solution

  • As per your comment, here's a schematic of how to dynamically add a script tag using XHR (XMLHttpRequest):

    var handleRequest = function( ) { //!! set up the handleRequest callback
    
         if(this.status != undefined) {
    
             /* do something with the status code here */
    
         }
    
         if(this.readyState == 4) {
    
              var script = document.createElement("script") ;
                  script.setAttribute("type","text/javascript") ;
              var text = document.createTextNode(this.responseText) ;
                  script.appendChild(text) ;
    
              var head = document.getElementsByTagName("head")[0] ;
                  head.insertBefore(script,head.firstChild) ;
    
         }
    
    } ;
    
    var request ; //!! supposing you have a way to get a working XHR Object
    
    //.. set the XHR Object
    
    request.open("GET",url,true) ;
    request.overrideMimeType("text/javascript") ;
    request.onreadystatechange = handleRequest ;
    request.send(null) ;
    

    Please keep in mind that this is only to give you an idea of what I mean. A working example would have to be way more elaborate judging from the jQuery source code.


    Links: