Jeremy Hixon

Web Developer

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.

// ===============================
// 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 && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
            script.onload = script.onreadystatechange = null;

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('', function() {
	getScript('js/script.js', function() {});