I made the following function, inspired by the jQuery's $.getScript method, it takes an url and a callback argument.
The callback is very useful, it is executed when the script has been loaded successfully, and you are ready to use it.
This function also takes care of removing the script elements from the DOM to avoid well known memory leaks:
loadScript("myLib.js", function () {
// myLib is loaded
//..
});
function loadScript(url, callback) {
var head = document.getElementsByTagName("head")[0],
script = document.createElement("script"),
done = false;
script.src = url;
// Attach event handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
callback(); // Execute callback function
// Prevent memory leaks in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}