When should we use async, defer, or normal JS execution?
<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.
</body> element, it becomes much less important to use an
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.