How to use the HTML Defer Attribute

In HTML, an attribute usually consists of an attribute name and an attribute value, such as in the anchor element example.

However, sometimes the value (behavior) is built-in to the attribute name.

For example, the defer attribute which we use to modify the HTML <script> element:

<script defer src="app.js"></script>

Notice that the defer attribute doesn’t have an assignment operator (=) or value because its behavior is built-in.

defer is a so-called boolean attribute. Booleans are used for a type of data that can only have two values, true or false (or enable/disable).

Let’s look take a closer look at the defer attribute.

This <script> element, without the defer attribute, will execute its src JavaScript code from the app.js value as soon as the browser has loaded it:

<script src="app.js"></script>

By default, HTML documents are parsed (read) from top to bottom, one line at a time. This means that if you put any JavaScript at the top of your document, it will execute before the rest of your document is done parsing.

That‘s the default behavior of the script element.

But when you add defer to the <script> element you disable that default behavior:

<script defer src="app.js"></script>

Now, the JavaScript code won’t execute until the entire page is finished loading.

In a literal sense, defer means put off/postpone/wait.

To beat the dead horse:

  • Without defer, JavaScript executes as soon as it as it’s loaded.
  • With defer JavaScript waits to execute until the entire HTML page is loaded.

If attributes confuse you, don’t worry, it always makes 10x more sense once you start using them in practice.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on