What do defer
and async
mean?
By default, a <script src=...></script>
tag is evil! The browser must halt parsing the HTML until the script is downloaded and executed (since the script might call document.write(...)
or define global variables that later scripts depend on). This means that any images and stylesheets that are after the script tag don't start downloading until after the script has finished downloading and executing. External scripts typically make the Web load much more slowly, which is why NoScript has become so popular.
Microsoft introduced defer
to solve the problem. If you use <script defer src=...></script>
, you promise not to call document.write(...)
. A defer
external script will start downloading immediately but won't execute until after the page is rendered. After the page has rendered, all defer
scripts are executed in the same order that they were declared. Not all browsers implement defer
yet.
HTML5 introduced the async
attribute which may execute any time--possibly before the page has finished parsing or even before other defer
/async
scripts that are still downloading. But it's harder to use multiple async
scripts because their execution order is not guaranteed. Like defer
, not all browsers implement async
yet.
After all defer
and async
scripts have executed, the DOMContentLoaded
and load
events fire.
A brief history of defer
and async
- 1997 IE 4 introduces
defer
.
- 1998 HTML 4 spec mentions
defer
, but unfortunately it doesn't say exactly when defer
scripts execute (All in order? Before onload
?). Thus, no other browsers implement defer
because no one wants to reverse-engineer IE's behavior or break scripts that might depend on IE's peculiarities. (See the Mozilla feature request, for example).
- 2006 HTML5 draft finally describes the details needed to implement
defer
: defer
scripts should all be executed in order after the rest of the page is parsed, and before onload
. It also introduces async
to specify scripts that can execute whenever they are downloaded without having to wait for each other. Unfortunately, HTML5 contradicts IE by not allowing inline defer
scripts. This breaks the invariant that all defer
scripts are executed in order (if some defer
scripts have src
and some have inline content).
- 2009 Gecko 1.9.1 (Firefox 3.5) supports
defer
.
- 2010-01 Gecko 1.9.2 (Firefox 3.6) supports
async
.
- 2010-09
defer
and async
are checked into Webkit. You should see it in Chrome and Safari very soon (it's already in the Chrome dev channel but it's a bit buggy).
- We're still waiting for Opera to implement
defer
and async
and for IE to implement async
.
So what should a web developer use?
There's no single rule to follow at this time. You have to choose the solution that best balances simplicity, page render latency, and script execution latency for the set of browsers that access your website.
- The simplest way to have the page render before the scripts execute, as others have pointed out, is to put your scripts at the bottom of the page. But if the scripts are essential, or the webpage contains lots of HTML, then you should put your scripts higher up on the page.
- If your script is standalone and your customers use IE or new versions of Firefox, use
<script async defer src=...></script>
: This allows rendering to continue in parallel to script downloading for IE and the newest HTML5 browsers but causes pre-HTML5 browsers (including all versions of Opera) to block.
- If one external script depends on another, mark them both
defer
(but not async
) and they will be executed in the order that they were declared (except IE<=9 in certain conditions can execute them out of order). Again, this allows rendering to continue in parallel to script downloading in IE and HTML5-aware Gecko/Webkit, but older browsers and Opera will suffer. It's a good idea to use defer
even if the scripts are at the bottom of the page so that they download in parallel with each other.
- Never use
defer
for inline scripts because the HTML5 draft has taken away the execution order guarantee.
- If your audience includes many Opera or old Firefox/Safari users, the following snippet will execute the script after parsing the document on most pre-HTML5 browsers (IE, Webkit, need to test old Firefox), while the newest HTML5-aware browsers start downloading immediately but won't block to execute the script because of the
async
attribute. In other words, most older browsers treat it like a script at the bottom of the page, and newest browsers recognize the async
. But Opera users get the worst of both worlds, because Opera begins execution immediately and doesn't understand async
. This is the pattern recommended by Google Analytics for the urchin on many webpages.
snippet:
<script>
(function() {
var script = document.createElement('script');
script.src = '...';
script.async = true;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(script, s);
})();
</script>
- If another script depends on the first script to load, then you can use the same pattern as above, but listen to the onload event of the first script element before executing the second script. See the LABjs example for how to wait for another script to load.
- If you have multiple scripts with complicated dependencies, use LAB.js or the YUI Loader to make them download in parallel and execute in some valid order.
- If you're using a popular library such as jQuery, consider using Google's copy rather than your own to increase the likelihood that the browser has already cached it.
Update: If you have scripts split into modules and want to improve performance, I recommend the "Coupling Asynchronous Scripts" chapter of Even Faster Web Sites by Steve Souder. It contains tips/tricks for not only controlling execution order but also to delay parsing of scripts to improve performance.
head
orbody
). The current best-practice advice is to place all scripts just before the closing</body>
tag. – Magnesium