Dynamically loading javascript files


Below is a little piece of code that helped us facilitate dynamically loading javascript files.

// Please go here for details on the script below:
// http://unixpapa.com/js/dyna.html
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute("id", id);
script.setAttribute("type", 'text/javascript');
script.setAttribute("src", url);
script.onload = function(){
   loadedCallback(sender, id);
};
script.onreadystatechange = function(){
   if (this.readyState == 'loaded' || this.readyState == 'complete') {
      loadedCallback(sender, id);
   }
};
head.appendChild(script);

As you can see the same callback loadedCallback(sender, id); is called twice. The first under the load function is only picked up by Firefox, Opera, etc. and the onreadystatechange is a Microsoft event. Took me forever to figure the Microsoft solution.

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: