I made the following function for being able to load JavaScript files programmatically:
Usage:
loadScript('http://site.com/js/libraryXX.js', function () {
alert('libraryXX loaded!');
});
Implementation:
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);
}
I use a callback function argument, that will be executed when the script is loaded properly.
Also notice that the script element is removed from the head after it is loaded and I remove the load and readystatechange events by setting them to null, that is made to prevent memory leaks on IE.
Check an example usage here.