Asynchronous JavaScript Files

It’s easy-peasy-lemon-squeezy with HTML5

The async attribute added to HTML5 makes the job all too simple:

async attribute
1
<script src="script.js" async></script>

This tells the browser to execute the script at the first opportunity after it has finished downloading, while the page continues parsing and before the window load event.

Pre-HTML5

I’m writing an embeddable widget at the moment and unfortunately, can’t rely on browser support for the async attribute. This makes me sad, as I really can’t block the page rendering.

Solution? Defer

There is a defer attribute, with pretty good support that will execute when the page has finished parsing. Not as good as executing while the page continues parsing though, like with the async attribute.

Below is a way to handle the deferred execution of JavaScript files that will work in all cases. It’s not perfect, the download doesn’t happen immediately like with the async or defer attributes. Also, it fires at the time of the window load event, not before like the native async attribute (which is included for good measure).

Here’s the general gist (untested):

general gist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function() {
"use strict";
function loadJSAsync() {
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "script.js";
js.async = true;
// insert the "js" script tag to the DOM here ...
}
if (window.attachEvent) {
window.attachEvent("onload", loadJSAsync);
} else {
window.addEventListener("load", loadJSAsync, false);
}
})();

It basically just delays adding the script tag to the DOM. Maybe there is a way to test for async or defer support and fall back to the window load event hack? I can’t wait for all these old browsers to disappear.