When should we use async, defer, or normal JS execution?

Abhay Jain
2 min readDec 24, 2020

--

JavaScript is considered a “parser blocking resource”. This means that the parsing of the HTML document itself is blocked by JavaScript. When the parser reaches a <script> tag, whether that be internal or external, it stops to fetch (if it is external) and run it.

Where is the <script> element located?

Asynchronous and deferred execution of scripts are more important when the <script> element is not located at the very end of the document. HTML documents are parsed in order, from the first opening <html> element to it's close.

Note: If an externally sourced JavaScript file is placed right before the closing </body> element, it becomes much less important to use an async or defer attribute. Since the parser will have finished the vast majority of the document by that point, JavaScript files don't have much parsing left to block.

Is the script self-contained?

For script files that are not dependent on other files and/or do not have any dependencies themselves, the async attribute is particularly useful. Since we do not care exactly at which point the file is executed, asynchronous loading is the most suitable option.

Does the script rely on a fully parsed DOM?

In many cases, the script file contains functionality that requires interaction with the DOM. Or, it may have a dependency on another file included on the page. In these cases, the DOM must be fully parsed before the script should be executed. Typically, such a file will be placed at the bottom of the page to ensure everything before it has been parsed. However, in situations where, for whatever reason, the file in question needs to be placed elsewhere, the defer attribute can be used.

Is the script a (small) dependency?

Finally, if the script is relatively small, and/or is dependent on other files, it may be more useful to have it defined inline. Although having it inline will block the parsing of the HTML document, it should not be a significant interference if it’s a small size. Additionally, if it is dependent on other files, minor blocking may be necessary.

In the V8 engine(used in Chromium), an attempt is made to parse all scripts, regardless of their attributes, on a separate dedicated thread for script execution. This way, the parser blocking nature of JavaScript files should be minimised as a default.

--

--

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.