What is the difference between async vs defer attributes
According to https://caniuse.com website, async and defer attributes for the <script>
element have great support and I think it might be a good time to learn what they do and how to use them.
JavaScript is considered a “parser blocking resource” causing blocking of HTML parsing. Thankfully, the latest technologies such as HTML5 gives you 3 ways to tell browser when to run JavaScript code.
<script>
<script src="myscript.js"></script>
The HTML is parsed until the <script>
tag is reached. At that point, parsing of HTML is blocked and a request is made to fetch the script file. Once the script is executed, HTML parsing resumes again.
<script async>
<script async src="myscript.js"></script>
With async (asynchronous) attribute, the HTML is parsed while the browser loads and execute the script at the same time. The script execution can happen whenever the script becomes ready (potentially before HTML parsing completes) after being fetched in parallel with the document parsing.
<script defer>
<script defer src="myscript.js"></script>
With defer attribute in place, the script file is downloaded in parallel while the HTML document is still parsing. However, even if the script file is fully downloaded long before the document is finished HTML parsing, the script is not executed until the HTML parsing is complete.
Note: The async and defer attributes are ignored for scripts that have no src attribute.
Usage
Use async attribute if the content of page does not rely on any scripts.
Use defer attribute if the content of page rely on script as you want to trigger this script when HTML is fully loaded.
Conclusion
The current trend is to put scripts in the <head>
tag and use the async or defer attributes as this allows your scripts to be downloaded asap without blocking your browser.
If you prefer to go with plain <script>
tag only, make sure to put it at the bottom before closing </body>
tag as this ensures the HTML parser isn’t blocked until the very end.