script tags at the bottom of the HTML, just before </body>. The browser may be unresponsive for a second or two, but it’s not noticeable because the main content has loaded.However, even that solution is inadequate for today’s multi-megabyte client-side applications. In extreme cases, it’s necessary to load large code libraries using
script tag injections or Ajax techniques. This prevents blocking, but requires additional code and rigorous testing to ensure that scripts run in the correct order in all browsers.
document.write or DOM modification nastiness:
<script src="file.js" defer></script>
The browser will begin to download file.js and other deferred scripts in parallel without stopping page processing.
defer was implemented in Internet Explorer version 4.0 — over 12 years ago! It’s also been available in Firefox since version 3.5.While all deferred scripts are guaranteed to run in sequence, it’s difficult to determine when that will occur. In theory, it should happen after the DOM has completely loaded, shortly before the DOMContentLoaded event. In practice, it depends on the OS and browser, whether the script is cached, and what other scripts are doing at the time.
async has been introduced in HTML5:
<script src="file.js" async></script>
async is identical to
defer, except that the script executes at the first opportunity after download (an optional
onload attribute can be added to run a specific function). You can’t guarantee that scripts will execute in sequence, but they will have loaded by the time the window
onload event fires.There’s support for
async in Firefox 3.6, Opera 10.5, and the latest WebKit build, so it should appear in the next versions of Chrome and Safari. IE9 is yet to support
async, but the IE team could easily add it as an alias for
defer. You can use both
Opera provides an experimental Delayed Script Execution facility, which can be enabled in about:config. It remembers where an
async script was loaded on the page, so it’s possible to use
document.write or modify the DOM.The feature would immediately benefit widgets and adverts that block page loading. Let’s hope Microsoft, Mozilla, and WebKit follow Opera’s lead.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.