September 15, 2024

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!

Stay up-to-date on the latest projects and articles from me