When you load a webpage then there are two major things happening in your browsers:
- HTML Parsing
- Loading of the scripts
Loading of the scripts contain two parts:
- Fetching the script from the network.
- Executing the script line by line.
<script> element has two attributes, async and defer, that can give us more control over how and when external; files are fetched and executed.
async and defer are boolean attributes that are used along with the
<script> tag to load the external scripts efficiently into your webpage.
<html> <head>...</head> <body> ... <script src="main.js"> ... </body> </html>
Suppose your browser is parsing the HTML and then it encounters the
In the case of the normal
<script> tag following steps takes place:
- JS blocks the parsing of HTML
- Fetches the script from the network
- Executes the script
- HTML parsing is started only after the script is fully executed
The async attribute is used to indicate to the browser that the script file can be executed asynchronously.
<script async src="main.js">
- While using the async attribute, meanwhile, the HTML parsing is going on, any of the script with the async attribute is fetched from the network asynchronously along with the HTML parsing.
As soon as scripts are fetched and available in the network, HTML parsing stops and scripts start executing.
Once the scripts are executed, the HTML parsing continues like regular.
<script defer src="script.js">
The defer attribute tells the browser to only execute the script file once the HTML document has been fully parsed.
In this case:
- HTML parsing goes on and scripts are fetched in parallel
- Scripts are only executed once the HTML parsing is complete.
This blog was originally posted at => [https://rahulism.tech/article/async-vs-defer-in-JS/]
😎Thanks For Reading | Happy Coding😃