The async
and defer
attributes are used with the <script>
element in HTML to control how external scripts are loaded and executed
.
async attribute - The async
attribute is a boolean attribute
. When you include the async
attribute in a <script>
tag, it indicates that the script should be executed asynchronously
. This means that the script will be downloaded in the background while the HTML document continues to be parsed.
- The script will be executed as soon as it's downloaded, regardless of whether the HTML parsing is complete.
- This is beneficial for non-blocking scripts, especially in scenarios where the script doesn't depend on the DOM structure or other scripts.
Syntax:
<script src="example.js" async></script>
defer attribute - The defer
attribute is a boolean attribute
. When you include the defer
attribute in a <script>
tag, it indicates that the script should be executed in order
, after the HTML document has been fully parsed.
- The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM.
- This is useful when the script depends on the DOM structure or other scripts and needs to be executed in a specific order.
Syntax:
<script src="example.js" defer></script>
Unless you're supporting ancient legacy systems, always add type="module"
to all your script tags:
<script type="module" src="main.js"></script> and place the tag inside <head>
<script defer nomodule> can be used as a legacy fallback.
As the name suggests, it allows you to import modules
, which makes it easier to organize your code. Enable strict mode
by default. This makes your code run faster, and reports more runtime errors instead of silently ignoring them. Execute your code only after the DOM has initialized
, which makes DOM manipulation easier. Thanks to this, you won't need to listen to load/readystatechange/DOMContentLoaded events. Prevent top level variables from implicitly polluting the global namespace. Allow you to use top-level await in supported engines. Load and parse your code asynchronously
, which improves load performance.