DEV Community

Cover image for Why you shouldn't use async and defer in the same script tag
Taha Shashtari
Taha Shashtari

Posted on • Originally published at tahazsh.com

Why you shouldn't use async and defer in the same script tag

To answer that question, let's first understand how <script> tags are downloaded and executed.

When the browser receives the HTML response, it starts parsing it incrementally from top to bottom. While parsing, if it encounters a <script> tag (without async or defer), it stops parsing the HTML until the JavaScript is downloaded and executed.

However, when using async or defer, the JavaScript will be downloaded (but not executed) in parallel with HTML parsing.

The key difference between async and defer is when the scripts are executed.

Async scripts will execute as soon as they are downloaded, which can pause the HTML parser.

Defer scripts will execute only after the entire page has been fully parsed and rendered.

Since async scripts execute before the page is fully ready, you might get errors when trying to access DOM elements from them.

On the other hand, defer scripts wait until the page is fully rendered, so you can safely access DOM elements from them.

What are async scripts useful for?

They are great for tasks that donโ€™t involve DOM manipulation. Examples are like analytics tools, fetching third-party ads, and social media widgets.

Because async scripts execute while the page is still being parsed, they are great for preparing and fetching data, like for ads, before the page finishes rendering. This can make the initial load faster.

What happens if you use both async and defer on the same script?

Most modern browsers prioritize async over defer, which can lead to errors if you try to access the DOM from that script.

Thatโ€™s why you should use either defer or async, but not both, for your scripts!


๐Ÿ”— Let's stay connected:

๐• Twitter/X: https://twitter.com/tahazsh
๐ŸŽฅ YouTube: https://www.youtube.com/@tahazsh
๐ŸŒ Blog: https://tahazsh.com/

Top comments (0)