Both async and defer are attributes that can be added to a script tag in HTML to control how the script is loaded and executed in the web page. Here are the differences between the two:
-
Execution:
- With
defer, the script is executed only after the HTML parsing is complete. - With
async, the script is executed as soon as it is available, regardless of whether or not the HTML parsing is complete.
- With
-
Order of Execution:
- With
defer, the order of execution of the scripts is maintained in the order they are specified in the HTML. - With
async, there is no guarantee of the order of execution of the scripts.
- With
-
Blocking:
- With
defer, the HTML parsing is not blocked while the script is being downloaded and executed. - With
async, the HTML parsing is blocked while the script is being downloaded and executed.
- With
When to use which one:
- Use
deferwhen the script does not depend on any other scripts or the DOM, and you want to maintain the order of execution of the scripts. - Use
asyncwhen the script is independent and can run in any order, and you want to speed up the loading of the page by downloading the script asynchronously.
It is also worth noting that both async and defer are not supported in all browsers, so it is important to test your code to ensure it works as expected.