2

I am using the following code snippet to load a javascript asynchronously, in a non-blocking manner. It works across Chrome, FF but fails to work in Internet Explorer.

I am running IE8 and can't hit the onload function in IE for the below code;

          <script type="text/javascript">
            (function () {
                var s = document.createElement('script');
                s.type = 'text/javascript';
                s.async = true;
                s.src = 'js/load_outer.js';
                s.onload = function () {
                    alert("Loaded");
                }

                var x = document.getElementsByTagName('script')[0];
                x.parentNode.insertBefore(s, x);
            })();
        </script>

Could anyone please help me identify the mistake?

Thanks

Jayesh
  • 3,891
  • 11
  • 55
  • 83
  • You may or may not get a "load" event when the script loads in IE. – Pointy Feb 24 '12 at 12:34
  • Here's a related question: [http://stackoverflow.com/questions/4845762/onload-handler-for-script-tag-in-internet-explorer](http://stackoverflow.com/questions/4845762/onload-handler-for-script-tag-in-internet-explorer). – jabclab Feb 24 '12 at 12:35
  • @jakeclarkson Thanks for the link. But, I had to avoid using any third party library – Jayesh Feb 24 '12 at 12:37

1 Answers1

2

IE (earlier than 9) doesn't support onload event for <script> element, use onreadystatechange instead:

var complete = false;
script.onload = script.onreadystatechange = function() {
    if (!complete && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
        complete = true;
        // your callback code here
    }
}
otakustay
  • 11,817
  • 4
  • 39
  • 43
  • 1
    This helped. I got stuck with a similar issue back with IE9. It gives double callbacks. Here is an article that solves that - http://www.aaronpeters.nl/blog/prevent-double-callback-execution-in-IE9 – Jayesh Mar 01 '12 at 11:58