'onload' handler for 'script' tag in internet explorer

I've been using this function to attach onload handler to a script tag, it seems to be the recommended way over the internet.
Yet, it doesn't work in internet explorer, if page is loaded already (tested in ie 8). You can see that it works in normal browsers (fires alert when script is loaded).

Am I missing something?
Thank you


Solution 1:

You should call jQuery.getScript, which does exactly what you're looking for.

EDIT: Here is the relevant source code from jQuery:

var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
if ( s.scriptCharset ) {
    script.charset = s.scriptCharset;
}
script.src = s.url;

// Handle Script loading
    var done = false;

// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
    if ( !done && (!this.readyState ||
            this.readyState === "loaded" || this.readyState === "complete") ) {
        done = true;
        jQuery.handleSuccess( s, xhr, status, data );
        jQuery.handleComplete( s, xhr, status, data );

        // Handle memory leak in IE
        script.onload = script.onreadystatechange = null;
        if ( head && script.parentNode ) {
            head.removeChild( script );
        }
    }
};

// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );

Solution 2:

I also had issues with script.onload = runFunction; in IE8.

I tried jQuery.getScript and it worked perfectly for my needs. The only downside is having to wait for jQuery to be loaded before adding in the script.

However, since my callback functions utilize jQuery very heavily anyway I find this an extremely acceptable and very minor downside since it creates a very easy to use, cross-browser solution.

Update:

Here is a way of doing it without using jQuery:

(a modified solution from: https://stackoverflow.com/a/13031185/1339954)

var url = 'http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js';
var headID = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.type='text/javascript';
script.src=url;

//for nonIE browsers
script.onload=function(){
        addVideo();
    }

 //for IE Browsers
 ieLoadBugFix(script, function(){
     addVideo();}
 );

function ieLoadBugFix(scriptElement, callback){
        if (scriptElement.readyState=='loaded' || scriptElement.readyState=='completed') {
             callback();
         }else {
             setTimeout(function() {ieLoadBugFix(scriptElement, callback); }, 100);
         }


 }

headID.appendChild(script);