async and defer attribute in the script tag?

async and defer attribute in the script tag?

ยท

2 min read

Table of contents

No heading

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.

Did you find this article valuable?

Support Saqib's blog by becoming a sponsor. Any amount is appreciated!

ย