Loading JavaScript Files Asynchronously

Moving all of your JavaScript files to the footer to delay parsing is a good way to speed up the render time of your website. If you want to speed it up even further you can load the scripts asynchronously so that the page load itself isn’t dependent on your scripts having been downloaded and cached at all.

<code>// ===============================
// Loading scripts anychronously
//
// Usage: getScript('script.js', function() { /* callback */ });
// ===============================
function getScript(url,success){
    var script = document.createElement('script');
    script.src = url;
    var head = document.getElementsByTagName('head')[0], done=false;
    script.onload = script.onreadystatechange = function(){
        if (!done &amp;&amp; (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    };
    head.appendChild(script);
}</code><a href="http://codepen.io/jeremyHixon/pen/lemgD">Check out this Pen!</a>


If you have more than one file and one file is dependent upon another you can chain them one at a time to insure you’re not getting any JavaScript errors from trying to run scripts when the libraries they are based on haven’t been loaded yet.

For instance if you’re using jQuery:

getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js', function() {
	getScript('js/script.js', function() {});
});

One Comment on “Loading JavaScript Files Asynchronously”

  1. Garison says:

    Change this:
    success();
    to this:
    if (success) success();
    and you won’t have to specify an empty function. You can just pass NULL for the end of the chain.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>