Deferred Loading with JavaScript - dummies

Deferred Loading with JavaScript

By Chris Minnick, Eva Holland

One major cause of slow web pages is the so-called blocking script. A blocking script is a JavaScript file whose loading and execution blocks the loading of a web page. In extreme circumstances, a browser may download an entire webpage and show a blank screen for several seconds or longer while the JavaScript is loaded and parsed. Because web users tend to become bored quickly, this situation should absolutely be avoided.

Fortunately, there are several ways to defer JavaScript loading and execution and to make your web pages display faster.

The first way is by using the defer attribute of the script element. Here’s what it looks like:

<script src="myscript.js" defer></script>

Note that the defer attribute can be used only with external JavaScript files. It can’t be applied to <script> blocks within a document.

When present, the defer attribute will cause the script to be executed once the page has finished parsing.

Another way to defer loading and execution of a script is the method recommended by Google. Google recommends putting the following code at the very bottom of your web page. To use it, you would replace the sample script name (here, myscript.js) with your own filename, of course.

<script type="text/javascript">
 function downloadJSAtOnload() {
 var element = document.createElement("script");
 element.src = "myscript.js";
 if (window.addEventListener)
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;

Another attribute for helping to defer JavaScript is the async attribute. The async attribute is new in HTML5. Here’s what it looks like:

<script src="myscript.js" async></script>

Like the defer attribute, the async attribute can only be used with external scripts (where the src attribute is used). When present, the async attribute will cause the script to be executed asynchronously with the rest of the page. In other words, the script will execute at the same time as the rest of the page.

Whichever method you choose to use may have an effect on whether the rest of the JavaScript on your page runs correctly. Make sure to test everything after implementing deferred loading. Done correctly, deferring JavaScript can dramatically decrease your users’ wait time and make everyone happier.