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);

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.