defer

The defer attribute in <script> tags delays script execution until after the document is fully parsed, improving loading time by preventing it from blocking page rendering.

defer Attribute

The defer attribute is a boolean attribute used in <script> tags. It ensures that a script executes only after the document has been fully parsed. This improves page loading performance by preventing scripts from blocking the rendering process. Scripts with defer run before the DOMContentLoaded event but after the HTML is completely loaded.

Syntax

index.html
<script defer>

Example

index.html
<script id="el" src="/example.js" defer></script>
script.js
const el = document.getElementById("el");
console.log(el.defer); // Output: true

Value

  • A boolean
The defer attribute in the <script> tag ensures that script.js runs only after the HTML document has been fully parsed, enhancing performance.

Explanation and Usage

The defer attribute allows scripts to load while the page is being parsed but delays execution until parsing is complete.

Key Differences Between Script Loading Methods

  • async: Loads and runs the script as soon as it is available, potentially interrupting page parsing.
  • defer (without async): Loads the script in parallel with page parsing but executes only after parsing is complete.
  • No async or defer: Loads and executes the script immediately, pausing page parsing until execution finishes.

Attribute Details

  • Boolean Attribute: The defer attribute does not require a value.
  • Applies To: Only used with the <script> element.

Conclusion

The defer attribute helps optimize webpage performance by ensuring scripts run only after the document is fully parsed. This prevents scripts from blocking rendering, leading to faster page loads and a smoother user experience. It is best suited for external scripts that interact with the document structure, making it a best practice for modern web development.