What Does the async Attribute on the HTML script Tag Do?

When async attribute is present on the HTML script tag, the script is loaded in an asynchronous way (i.e. it is loaded in the background and run when it's ready). This is in contrast to it being loaded in a parser-blocking way (when defer or async attributes are not present). In that case, the browser waits till the script is loaded and evaluated before continuing the parsing of the rest of the document.

When you mark a script as async:

  1. It is fetched in parallel to the parsing of the document (in a non-blocking way);
  2. It interrupts the parsing of the document once it has been downloaded, and is then executed/evaluated as soon as possible, before the parsing of the rest of the document continues;
  3. Its order of execution is not guaranteed;
  4. It may load before, or even after, the DOMContentLoaded event is fired (depending on how long the loading and execution of the script takes).

async is a boolean attribute that only works on external scripts (when the src attribute is present). The presence of the async attribute means that the script is loaded in an asynchronous way, while its absence means the opposite:

<script src="path/to/script.js" async></script>

You should mark a script as async when you want to load the script in a non-blocking way, and:

  • Its order of execution is not important;
  • It does not matter whether the script is loaded before or after DOMContentLoaded is fired;
  • It does not have any dependency on other scripts, and other scripts have no dependency on it.

This is mostly suited for scripts like analytics, ads, etc. to improve the performance of your page/app.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.