Both async
and defer
are boolean attributes that can be added to <script>
tags in HTML to control how JavaScript files are loaded and executed in a web page, but they behave differently:
async
Attribute:
- Scripts with the
async
attribute are fetched asynchronously (in parallel with the HTML parsing) and executed as soon as they are available. - Scripts loaded using the
async
attribute will download the script without blocking the page while the script is being fetched. - However, once the download is complete, the script will execute, which blocks the page from rendering.
- This means that the rest of the content on the web page is prevented from being processed and displayed to the user until the script finishes executing.
- The execution of these scripts is not guaranteed to be in order if there are multiple scripts with
async
. - The
async
attribute is ideal for scripts that are independent of other scripts and do not need to manipulate the DOM immediately after the page loads (e.g., analytics scripts).
Example:
<script async src="js/query/jquery.js"></script>
<script async src="js/script1.js"></script>
<script async src="js/script2.js"></script>