Taha

Why shouldn't you 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!

Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.