I made the following function based on the jQuery $.getScript , it takes url and callback arguments.
The callback is very useful, it is executed when the script has been successfully loaded, and you are ready to use it.
This function also takes care of removing script elements from the DOM to avoid 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); }
source share