What Does the defer Attribute on the HTML script Tag Do?

Find out what adding the defer attribute to HTML script tag means

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:

  1. It is fetched in parallel to the parsing of the document (in a non-blocking way);
  2. It does not interrupt the parsing of the document once it has been downloaded;
  3. It is executed/evaluated just before DOMContentLoaded event is fired;
  4. It prevents the DOMContentLoaded event from firing until the script has been loaded and finished evaluating;
  5. 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.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.