top of page
Search
Writer's pictureMatt Burrell

Maximizing Performance with the HTML defer Attribute

The defer attribute is an optional attribute used in an HTML script tag to specify that the script should be executed after the page has finished parsing. This can be useful in several situations, including:


  • When the script is used to enhance the page's performance, such as by asynchronously loading content or adding event listeners.

  • When the script relies on elements that are not yet present in the DOM when the script is encountered.

  • When the script is used to set up or modify the behaviour of other elements on the page, and this setup must happen after the page has been fully parsed.


To use the defer attribute, add it to a script tag like so:

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

Note that the defer attribute only works with external scripts (those with a src attribute). It does not affect inline scripts (those with script content between the script tags).


One potential downside to using the defer attribute is that it can cause the script to be executed later than if it were included in the page without the defer attribute. This can be an issue if the script is needed to be run as soon as possible, such as when it is used to display important content or to set up critical functionality. In these cases, it may be better to omit the defer attribute and place the script at the end of the body element instead.


Overall, the defer attribute can be a useful tool for optimizing the performance and behaviour of a webpage, but it's important to carefully consider its use case before implementing it.

Recent Posts

See All

Debunking Monorepo Myths

A monorepo is a version control strategy where multiple projects are stored in a single repository. I've noticed that some developers...

bottom of page