What is the use of the defer attribute in the HTML <script> tag?
In this Answer, we'll learn about the defer attribute of the HTML <script> tags. The defer attribute is a
Note: The
deferattribute can only be used when JavaScript is externally linked to the HTML file using thesrcattribute of the<script>tag.
Syntax
<script defer></script>
Example
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="styles.css"/>
</head>
<body>
<div id="content">
<h2 class="Headings">The defer attribute in HTML script tags</h2>
<img src='logoMarkv2.png'/>
<script defer src="./long.js"></script>
<script defer src="./small.js"></script>
<h3 class="Headings">Welcome to Educative Answers!</h3>
</div>
</body>
Explanation
The explanation that follows from the code widget above is as follows:
Line 3: In this line of code, we have a
<link>tag that links tostyles.cssusing thehrefattribute. This file contains all the styling and formatting required for our page.Lines 6–12: This piece of code renders the content of the HTML page, which is enclosed by the
<div>tag. The content composes of the following HTML elements:Line 7: This line contains the
<h2>tag, which renders the bold heading at the top of our HTML page.Line 8: Here, we have used the
<img>tag to display the logo of Educative to make our web page more presentable.Lines 9–10: These lines contain
<script>tags that link tolong.jsandsmall.jsrespectively with the help of thesrcattribute. Additionally, we specify thedeferattribute so that the browser fetches these JavaScript files simultaneously but executes them once it is done with parsing.Line 11: This line again contains an
<h3>tag used to make up the page's content.
The content inside the long.js and small.js file is just for the sake of demonstration. Each file ends with JavaScript alert to display a message to the user. To read more on alert, please refer to this Answer.
Note: The scripts loaded using
deferattribute are always running in the sequence as defined by the code. In our example, this is depicted as thealertforlong.jsappears first and is then followed by thealertinsmall.js.
Free Resources