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
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
- It is fetched in parallel to the parsing of the document (in a non-blocking way);
- 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;
- Its order of execution is not guaranteed;
- It may load before, or even after, the
DOMContentLoadedevent 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
- 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.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.