Wednesday, December 25, 2013

Load JavaScript Dynamically

Recently in one of my project we have requirement to load JavaScript file dynamically and call a specific function after the script is loaded. Following is the function you can use for it.

function loadJavaScriptOnDemand(src, callback) {
    var script = document.createElement('script');
            script.src = src;
    document.getElementsByTagName('head')[0].appendChild(script);
    
    script.onreadystatechange = function() {
        if (script.readyState == 4 || script.readyState == "complete") {

            if (typeof callback == "function") {
                  callback();
            }
            callback = null;
        }
    }

}

Above function you can call as following.

loadJavaScriptOnDemand('path/to/your/javascript',function(){alert('JavaScript loaded')});

If you above function we have added onredaystatechnage events for the the script. Since this will be asynchronous loading we have to check the state for the progress and call the callback function once the script is loaded completely.

Hope this helps you.

No comments:

Post a Comment