defer Attribute
The <script> tag with the defer attribute downloads the script asynchronously during document parsing but delays execution until after the entire document parsing is complete and before the DOMContentLoaded event is triggered. This ensures that scripts with defer execute after the document parsing is complete, guaranteeing that the DOM is fully built when they run.
Example:
html<script src="example.js" defer></script>
If you have multiple scripts with the defer attribute, they will execute in the order they appear in the document, even if some scripts download earlier than others.
async Attribute
The async attribute also allows scripts to be downloaded asynchronously during document parsing, but it executes immediately once the download is complete, which may occur before the rest of the document is parsed. Therefore, scripts using async do not guarantee execution in the order they appear on the page, nor do they ensure that the DOM is fully built.
Example:
html<script src="example.js" async></script>
async is suitable for scripts that do not depend on other scripts or the DOM, such as ad loading or tracking scripts.
Summary
deferensures that scripts execute after the document is fully parsed and the DOM is built, but before the DOMContentLoaded event is triggered.asyncensures that scripts execute as soon as they are downloaded, but may interrupt the document parsing process.<script>tags without these attributes download immediately and block document parsing until the script execution is complete.
In practical applications, choosing between defer and async depends on the script's dependency on document parsing and the dependencies between scripts. If you need to ensure scripts execute in order and after the DOM is fully built, defer is the better choice. If the execution order is not important and you want to fetch and execute the script as soon as possible, you can use async.