When defer
attribute is present on the HTML script
tag, the script is loaded in the background, but not executed till:
- The document is parsed, and;
- DOM is fully built.
In contrast, the default behavior is to load the script in a parser-blocking way (i.e. when defer
or async
attributes are not present). In that case, the browser waits till the script is loaded and executed before continuing the parsing of the rest of the document.
When you mark a script
as defer
:
- It is fetched in parallel to the parsing of the document (in a non-blocking way);
- It does not interrupt the parsing of the document once it has been downloaded;
- It is executed/evaluated just before
DOMContentLoaded
event is fired; - It prevents the
DOMContentLoaded
event from firing until the script has been loaded and finished evaluating; - It is executed in the order in which it appears in the document; this means that its order of execution is guaranteed.
defer
is a boolean attribute that only works on external scripts (when the src
attribute is present). The presence of the defer
attribute means that the evaluation of the script
is deferred, while its absence means the opposite:
<script src="path/to/script.js" defer></script>
You should mark a script as defer
when:
- You want to load the script in a non-blocking way and execute it only when DOM is ready;
- The order in which the script is executed is important;
- It matters that the script is loaded before
DOMContentLoaded
is fired; - It has dependencies on other scripts or DOM elements, which must be ready/available before the script is executed/evaluated.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.