Skip to main content

Adding Scripts

Loading and executing the script specified in the <script> tag with no attributes will block HTML document processing and DOM building. This is a problem.

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

When the analyzer sees such a tag, the processing of the HTML document is suspended and files of the script specified in the src attribute begin to load. After loading, the script is executed, and only then HTML processing resumes. This is called a "blocking" script.

The defer and async attributes were introduced to give developers more control over how to load scripts and when to execute them.

defer attribute

<script defer src="path-to-script.js"></script>

The defer attribute instructs the browser to load the script file in the background, together with HTML document processing and DOM building. The script will only be executed after the HTML document has been processed and DOM has been built. Such scripts do not block the process of DOM tree creation and are guaranteed to be executed in the order in which they are specified in the HTML document.

defer attribute

async attribute

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

Loading a script with the async attribute does not block DOM building, but it is executed immediately after loading. This means that such scripts cannot block DOM building, and they are executed in no particular order.

async attribute