Dynamic script loading in IE

For past few days I was trying to load an external Javascript file dynamically in my web page. It was working fine in FF but strangely wasn’t working in IE. Finally got the crack. Thought of sharing it here.

Consider the given code piece.

var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-1.4.2.min.js";
script.onload = function(){
alert($(document).length);
};
document.getElementsByTagName('head')[0].appendChild(script);

You make a script tag. Set its source to latest version of jQuery file. Then try to use jQuey. In FF this code will work fine. But in Internet Explorer, you will notive that execution doesn’t go inside the onload function, even after script is loaded. Here is how you need to do it in IE.

var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-1.4.2.min.js";
script.onreadystatechange = function() {
if(script.readyState=='loaded'){
alert($(document).length);
}
};
document.getElementsByTagName('head')[0].appendChild(script);

In IE, its the state which triggers the methods. So on different times, the script element can have different states. For example, loading or loaded. When ever the state is changed, onreadystatechange method is called. You can put your handlers there depending on what you want to perform for which state. For the given case, you need to check for the state loaded. Once you are inside the check, your handler will be executed.

You can have a check for your browser and depending on that, you can put handlers accordingly.

Note: It has been tested with IE7 and IE8.

One thought on “Dynamic script loading in IE

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>