Table of contents
No headings in the article.
Both are boolean attributes that are used along with the script tag to load external scripts into our webpage. Let's discuss all three scenarios using a normal script tag and with async and defer attributes.
๐๐จ๐ซ๐ฆ๐๐ฅ ๐๐๐ซ๐ข๐ฉ๐ญ ๐ญ๐๐ : In the normal script tag, the browser will parse the HTML line by line until it encounters the script tag. So what happens is the browser will stop HTML parsing and it will fetch scripts from the network and execute it. Once the script is fully executed then only the browser will continue to parse HTML.
In a normal script tag, you do not need to write any attribute.
<๐ฌ๐๐ซ๐ข๐ฉ๐ญ ๐ฌ๐ซ๐="๐ฌ๐๐ซ๐ข๐ฉ๐ญ.๐ฃ๐ฌ"></๐ฌ๐๐ซ๐ข๐ฉ๐ญ>
๐๐ฌ๐ฒ๐ง๐ ๐ข๐ง ๐ฌ๐๐ซ๐ข๐ฉ๐ญ ๐ญ๐๐ : Using async attribute in the script tag, scripts are fetched from the network asynchronously or in parallel with the HTML parsing. The browser will not block the HTML parsing in this case.
As soon as the scripts are available, it will pause the HTML parsing and execute the scripts. Once scripts get executed then only the browser continues to parse HTML.
To use async, simply add "async" attribute in your script tag as given below:
<๐ฌ๐๐ซ๐ข๐ฉ๐ญ ๐๐ฌ๐ฒ๐ง๐ ๐ฌ๐ซ๐="๐ฌ๐๐ซ๐ข๐ฉ๐ญ.๐ฃ๐ฌ"></๐ฌ๐๐ซ๐ข๐ฉ๐ญ>
๐๐๐๐๐ซ ๐ข๐ง ๐ฌ๐๐ซ๐ข๐ฉ๐ญ ๐ญ๐๐ : By using defer attribute in the script tag, HTML parsing continues goes on and the scripts are fetched in parallel. But these scripts are only executed once the HTML parsing is done. It doesn't matter whether the scripts are available in our browser or not.
To use defer, simply add "defer" attribute in your script tag as given below:
<๐ฌ๐๐ซ๐ข๐ฉ๐ญ ๐๐๐๐๐ซ ๐ฌ๐ซ๐="๐ฌ๐๐ซ๐ข๐ฉ๐ญ.๐ฃ๐ฌ"></๐ฌ๐๐ซ๐ข๐ฉ๐ญ>
In this article, We have discussed how async and defer attributes work in the script tag. Understanding when to use each one will help you create a faster and more efficient webpage.
Thank you for reading, if you learn something new from this article please give it a like and share It with other javascript developers.