Briefly
Scripts with the defer
attributes are loaded and executed sequentially, while those with async
are loaded asynchronously. In addition, defer
always waits until the entire HTML document is ready, while async
executes immediately after loading.
How to Write
Both attributes are boolean. This means that they do not need to have a value assigned. If the attribute is specified, the browser interprets this as a command to act. To cancel the effect, simply remove the attribute.
How to Understand
Usually, browsers load <script>
synchronously during the parsing of the document. Therefore, it is common to add scripts at the end of the document, before <
, to prevent them from slowing down the page load. However, with the defer
and async
attributes, you can explicitly manage the order in which scripts are loaded and executed.
async
Attribute
Instructs the browser to load the script asynchronously if possible.
The script runs completely asynchronously. This means that the file will execute without waiting for the loading and display of the web page. Upon encountering <script async src
, the browser does not stop processing the page but continues working. When the script is loaded, it will execute.
<script src="script1.js" async></script><script src="script2.js" async></script>
<script src="script1.js" async></script> <script src="script2.js" async></script>
The script that loads faster will execute first.
Supported by all browsers except IE9-.
defer
Attribute
Instructs the browser that the script should be executed after the document has been parsed but before the DOM
event.
Scripts with the defer
attribute will prevent the DOM
event from firing until the script has fully loaded and its initialization has completed.
<script src="script1.js" defer></script><script src="script2.js" defer></script>
<script src="script1.js" defer></script> <script src="script2.js" defer></script>
script1
, which is included first, will always execute first. Even if script2
loads earlier, it will be executed after the first script.
Application
In practice, defer
is used for scripts that require access to the entire DOM tree or if the order of execution is important.
And async
is good for independent scripts, such as counters and ads, where the order of execution does not matter.
Tips
💡 A dynamically inserted <script>
(for example, inserted with document
) is loaded asynchronously by default by the browser.