Open In App

What is the use of defer Attribute in <script> Tags ?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The “defer” attribute in <script> tags are used to specify that the script should be executed after the HTML document has been parsed. This attribute is primarily used to improve page loading performance by deferring the execution of non-essential scripts until after the document has been fully loaded, allowing for faster rendering and improved user experience.

Syntax

<script src="script.js" defer></script>
Key Point Description
Deferred Execution Scripts with the “defer” attribute are executed in the order they appear in the document after the document has been parsed but before the DOMContentLoaded event is fired.
Improved Performance Deferring script execution helps improve page loading performance by allowing the browser to render content without blocking scripts that are not immediately necessary.
Compatibility The “defer” attribute is supported by most modern web browsers and is commonly used for scripts that do not need to be executed immediately.
Execution Order If multiple scripts have the “defer” attribute, they are executed sequentially in the order they appear in the document, after the parsing of the HTML content.

Features

  • Basic Usage: Apply the “defer” attribute to script tags to defer their execution until after the HTML document has been parsed.
  • Page Loading Optimization: Use “defer” for scripts that are not critical for initial page rendering, such as analytics scripts or scripts for non-essential functionality.
  • Event Handling: Scripts with the “defer” attribute are executed before the DOMContentLoaded event is fired, allowing them to access and manipulate the DOM once it’s fully constructed.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads