In this Answer, we'll learn about the defer
attribute of the HTML <script>
tags. The defer
attribute is a
Note: The
defer
attribute can only be used when JavaScript is externally linked to the HTML file using thesrc
attribute of the<script>
tag.
<script defer></script>
<!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>
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 to styles.css
using the href
attribute. 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 to long.js
and small.js
respectively with the help of the src
attribute. Additionally, we specify the defer
attribute 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
defer
attribute are always running in the sequence as defined by the code. In our example, this is depicted as thealert
forlong.js
appears first and is then followed by thealert
insmall.js
.
Free Resources