leodutra
7/26/2016 - 5:43 PM

Loads JavaScript file dynamically in a HTML app.

Loads JavaScript file dynamically in a HTML app.

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (this.readyState == "loaded" || this.readyState == "complete"){
                this.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            this.onload = null;
            callback();
        };
    }

    script.src = url;
    
    // Fire the loading
    head.appendChild(script);
}