A first look at the difference between using async vs defer for the html script tag.
Let's say we have the below html code:
<script src="my-script.js"></script>
When the html parser reaches a script
tag like the one above, it will do the following:
- pause the parsing of the document
- do a request to download the
my-script.js
script file - wait for the file to download
- execute the script contents after it was fully downloaded
- resume the parsing of the document
This can lead to a bad experience for our users, given that they need to wait for both the downloading and the execution of the scripts before they can interact with the page.
In order to mitigate this we have 2 attributes we can use on the script tag: async
and defer
.
The HTML script async attribute
Adding the async
attribute to a script tag signals the browser to download the script file in parallel with the parsing of the document, and when the script file has fully downloaded the parsing of the document will be paused and the script executed. After the execution, the parsing will be resumed.
Code example:
<script src="my-script.js" async></script>
The HTML script async attribute
The defer
attribute will also signal the browser to download the script file in parallel with the parsing of the document, but the execution of the script will take place only when the parser has fully completed its job.
Code example:
<script src="my-script.js" async></script>
Added this table to summarize all of this:
Syntax | How it is downloaded | When it is executed |
---|---|---|
script src="..." | pauses the parsing | after the script is downloaded |
script src="..." async | in parallel with the parsing | after the script is downloaded |
script src="..." defer | in parallel with the parsing | when the parsing is done |
Some notes on the defer
and async
attributes:
- if we dynamically import a js script, then that script is considered async by default
- as an extra performance boost we can also have the decoding of images done with async
- use the async attribute for scripts that do not depend on other scripts. For example a Google Analytics script. The async attribute does not guarantee the order of execution.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.