tl;dr; async
scores slightly better that defer
(on script
tags) in this experiment using Webpagetest.
Much has been written about the difference between <script defer src="...">
and <script async src="...">
but nothing beats seeing it visually in Webpagetest.
Here are some good articles/resources:
- async vs defer attributes
- Script Tag - async & defer
- Prefer DEFER Over ASYNC
- Asynchronous vs Deferred JavaScript
So I took a page off my own blog. Butchered it and cleaned up the 6 <script>
tags. It uses HTTP/2 and some jQuery and some other vanilla JavaScript stuff. See the page here: neither.html
Then I copied that HTML file and replaced all <script src="...">
with <script defer src="...">
: defer.html. And lastly, the same with: async.html.
First let's compare all three against each other:
Neither vs defer vs async on Webpagetest.
Clearly, making the JavaScript non-blocking is critical for web performance. That's 1.7 seconds instead of 2.8 seconds.
Second, let's compare just defer
vs. async
on a 4G connection:
defer
vs. async
on 4G
Also, if you like here's defer
vs. async
on a desktop browser instead.
Conclusions
-
Don't allow your JavaScript to block rendering unless it's OK to have your users staring at a white screen till everything has landed.
-
There's not much difference between
defer
andasync
.async
has a slight advantage as per these experiments. I'm only capable of guessing, but I suspect it's because it can "spread out" the work better and get some work done in parallel whilstdefer
has things that tell it to wait. In particular, since withdefer
the order of the<script>
tags is respected. Suppose that the filesome.jquery.plugin.js
downloads beforejquery.min.js
, then that file has to be blocked and execution delayed whilst waiting forjquery.min.js
to download, parse and execute. Withasync
it's more of a wild west of executing whenever you can. -
The async.html is busted because of the unpredictable order of execution and these
.js
files depend on the order. Another reason to usedefer
if your scripts have that order-dependency problem. -
Consider using a mix of
async
anddefer
.async
has the advantage that some parsing/execution can be done by the main thread whilst waiting for other blocking resources like images.
Comments