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
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
- 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
DOMContentLoadedevent is fired;
- It prevents the
DOMContentLoadedevent 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
- 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
- It has dependencies on other scripts or DOM elements, which must be ready/available before the script is executed/evaluated.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.