Last Updated: September 02, 2019
·
3.162K
· francisc

Asynchronous Script Loading

This is what I use to asynchronously load scripts. It's for simple async script loading rather than full dependency management. For that you should use something like the wonderful Require.js.

Here's an example for when it might come in handy: loading the Google Maps API when you are using it only on one page of your website (e.g. Contact). No point in loading the script on every page if you only use it on one.

function asyncLoad(scriptURL,callback)
{
    if(!scriptURL){return;}
    var firstScriptTag=document.getElementsByTagName('script')[0];
    var js=document.createElement('script');
    js.type='text/javascript';
    js.src=scriptURL;
    js.async=true;

    if(callback && typeof(callback)===typeof(Function))
    {
        //Modern browsers (IE9+)
        if(js.addEventListener)
        {
            js.addEventListener('load',callback,false);
        }
        else//(IE8-)
        {
            js.onreadystatechange=function()
            {
                if(js.readyState in {loaded:1,complete:1})
                {
                    js.onreadystatechange=null;
                    callback();
                }
            };
        }
    }

    firstScriptTag.parentNode.insertBefore(js,firstScriptTag);
}

Usage:

asyncLoad('some/local/script.js',someFunction);
function someFunction()
{
    //script.js loaded
}

asyncLoad('http://code.jquery.com/jquery-1.8.0.min.js',function()
{
    //$===jQuery
});

Special thanks to Stoyan Stefanov who's article inspired most of the code in the function above.