async and defer attributes are both used to control script behavior during HTML page loading. They are both attributes of the <script> tag. Their primary purpose is to optimize page load time, but they function differently.
async attribute
When you use the async attribute in the <script> tag, it instructs the browser to load the JavaScript file asynchronously. This means the browser can continue parsing the rest of the HTML page without waiting for the script to finish loading and executing. Once the script file is loaded, the browser interrupts page parsing to execute it.
Usage scenario example:
For example, if you have a third-party script for user behavior analysis, such as Google Analytics, you can use the async attribute to load it, as it has minimal impact on initial page load performance and its loading order typically does not affect site functionality.
html<script async src="https://www.google-analytics.com/analytics.js"></script>
defer attribute
When using the defer attribute, the script is loaded asynchronously, but unlike async, it executes after the entire page has been parsed but before the DOMContentLoaded event is triggered, in the order they appear in the document.
Usage scenario example:
For example, if your webpage depends on one or more JavaScript files to correctly render page content or functionality (e.g., dynamically generating parts of the page with JavaScript), using the defer attribute is very useful because it ensures the script executes after the entire page is parsed while maintaining execution order.
html<script defer src="scripts.js"></script>
Summary
- async: Suitable for independent scripts that do not depend on other scripts and are not depended upon by other scripts, such as ad scripts or counters.
- defer: Suitable for scripts that require execution order to be maintained and must execute after the entire page is parsed, such as scripts dependent on the HTML page.
The choice between async and defer depends on the relationship between the script and page content, as well as dependencies between scripts.