JavaScript Loading Strategies in Web Page: async and defer


<script>
tags are used to download and execute JavaScript on a web page.
Consider these three operations on a web page:
HTML Parsing
JavaScript Download
JavaScript Execution
We can manipulate the sequence of these phases using the following attributes in the <script>
tag:
async (
<script async src=''></script>
)defer (
<script defer src=''></script>
)
Default Behavior:
By default (<script src=''></script>
), the script tag blocks HTML parsing until the JavaScript is downloaded and executed. This means that the browser will stop parsing the HTML, download the script, execute it, and then resume parsing the HTML.
async
and defer
Behavior:
Both async
and defer
do not block HTML parsing during the JavaScript download. The script download and HTML parsing happen simultaneously.
defer
ensures that the JavaScript is executed after the HTML parsing is completed. This means that all deferred scripts are executed in the order they appear in the document, but only after the entire HTML has been parsed.async
ensures that the JavaScript is executed as soon as it is downloaded, without waiting for the HTML parsing to complete. This can result in the script executing before, during, or after HTML parsing, potentially interrupting it.
Use Case
Use
async
, when a script has no dependency on othersUse
defer
when the script depends on other scripts
Subscribe to my newsletter
Read articles from Shams Nahid directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Shams Nahid
Shams Nahid
A lifelong learner. Love to travel. Listen to music.