Asynchronous JavaScript loading

If your website has a sufficient amount of static content, it might be a good idea to load all the extra JavaScript files asynchronously. Thismy old blog, for example, shows the static content as soon as possible, allowing its visitors to read the main content (the article) while the not-so-important content (like Facebook Like buttons, “Web 2.0” widgets and all that crap) is on its way from the server.

I use the following snippet to load external JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(function () {

    // Asynchronous JS loader
    var load = (function () {
        // Private members
        var create = function (url) {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.async = true;
            script.src = url;
            document.getElementsByTagName('head')[0].appendChild(script);
        };
        // Public: export a Function object
        return function (url) {
            setTimeout(function () { create(url); }, 1);
        };
    })();

    // Call the other script files from here
    load('http://www.example.com/foo-script.js');
    load('/media/js/some-local-js-file.js');

})();

I put all that stuff in a closure so nothing gets exported to to the global namespace. Note that the setTimeout trick is from here.

Note also that some JavaScript files will not work if you load them like this. These are ones that expect to be run before DOM readyness. Such an example is less.js.

Good candidates for asynchronous loading are the Facebook JavaScript SDK and Google Analytics.

Update