JavaScript loader

JavaScript loaders are great for managing and standardizing the way you load scripts on your site. Loaders create one location for all of your script information and a centralized location makes upgrading, removing or modifying information very easy.

Storing the site’s JavaScript information

The purpose of using a JavaScript loader is to make it easier for you to manage and load your site’s JavaScript files. That being said, we’ll need to save the script information somewhere on your site. There’s a few different techniques you can use but I found it easier to save the info in a global variable.

Format example

var scriptArray = [];
scriptArray['jquery'] = {
    'url': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
    'loaded': false
};
scriptArray['script'] = {
    'url': '//example.com/script.js',
    'loaded': false
};

Loader function

With mobile browsing on the rise, it’s important to load your site as efficiently as possible because not everyone has access to a fast internet connection. The script below takes advantage of asynchronous JavaScript loading to give the illusion that the site has loaded faster than it actually has.

function asyncLoad(js, callback) {
    var obj = scriptArray[js.toLowerCase()];
    if (obj && !obj.loaded) {
        var g = document.createElement('script'),
        s = document.getElementsByTagName('script')[0];
        g.src = obj.url;
        obj.loaded = true;
        if(callback) {
            g.onload = callback;
        }
        s.parentNode.insertBefore(g, s);
    }
}

JavaScript loader in action

Load your scripts by calling the function as shown below.

asyncLoad('script');

If you’d like to use a callback, pass it to the function like this.

asyncLoad('jquery', callback());