DEV Community

Rahul Kumar Jha
Rahul Kumar Jha

Posted on

Understanding <script async> vs <script defer> in HTML

When adding JavaScript to your webpages, you might notice two common script attributes: async and defer. Both help improve page load performance, but they behave differently.

async: Load and Run As Soon As Possible
When you use , the browser downloads the script while parsing the HTML. As soon as the script is ready, it executes—possibly before the rest of your HTML is finished loading. This is great for scripts that don’t depend on the DOM or other scripts, but it can cause problems if your script needs the HTML to be fully loaded.

defer: Wait Until HTML Is Ready
With , the script is also downloaded during HTML parsing, but it only runs after the HTML is fully parsed. This means your script can safely interact with the DOM, and multiple deferred scripts will execute in the order they appear.

In Summary:

Use async for independent scripts that don’t rely on the DOM.
Use defer for scripts that need the DOM to be ready or must maintain order.
Choosing the right attribute can make your pages both faster and more reliable!

Top comments (0)