Search code examples
javascriptinternet-explorer-11

script.readyState is undefined in IE11 & FF


I just worked on a dynamic script loader which works fine in IE9 but not in IE11 and not in FF.

Here is my code:

function getResourceScript(filename)
{
    var script = document.createElement('script');
    script.setAttribute('src', mShuttlePath + "scripts/" + filename);
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('language', 'javascript');
    document.getElementsByTagName('head')[0].appendChild(script);
}

function documentLoadInit()
{
    if (document.readyState == 'complete')
    {
        // check if all scripts are loaded
        for (var n = 0; n < document.scripts.length; n++)
        {
            if (document.scripts[n].readyState != "complete" && document.scripts[n].readyState != "loaded")
            {
                setTimeout(documentLoadInit, 49);
                return false;
            }
        }
        Init();
    }
    else
    {
        setTimeout(documentLoadInit, 49);
    }

}
getResourceScript("core/core.js");
getResourceScript("core/ajax.js");

The main problem here is, that the script.readyState is dropped in IE11 - so much I found out!

But how to replace it? How to check When the script is loaded / is finished?

Any ideas?


Solution

  • From the MSDN:

    Note: For the script element, readyState is no longer supported. Starting with Internet Explorer 11, use onload. For info, see Compatibility changes.

    So, instead of checking for the readyState you can use something like this:

    if (!script.addEventListener) {
        //Old IE
        script.attachEvent("onload", function(){
            // script has loaded in IE 7 and 8 as well.
            callBack();
        });
    }
    else
    {
        script.addEventListener("load", function() {
            // Script has loaded.
            callBack();
        });
    }
    

    Also, I'm pretty sure that you can improve your code. And setInterval() is more suitable in this case. Read a little bit about how to use dom events and if you still have compatibility issues, here is something that you could use:

    function loadExtScript(src, test, callback) {
      var s = document.createElement('script');
      s.src = src;
      document.body.appendChild(s);
    
      var callbackTimer = setInterval(function() {
        var call = false;
        try {
          call = test.call();
        } catch (e) {}
    
        if (call) {
          clearInterval(callbackTimer);
          callback.call();
        }
      }, 100);
    }
    

    The function takes a test as a parameter. Since you are the designer of the app, you’ll know what successful test is. Once this test is true, it will execute the callback.