The HTML defer attribute is used in an external <script> tag to specify that the script should be executed only after the HTML document has been completely parsed.
Definition and Usage
➔ The external script is executed after the HTML document is fully parsed but just before the DOMContentLoaded event is fired.
➔ The process is non-blocking which means the script can download in parallel with document parsing.
➔ Using the defer attribute improves page load performance and user experience.
➔ The defer attribute can also handle script dependencies on other scripts.
Syntax
<script src="myscript.js" defer></script>
Example (Blocking)
<!DOCTYPE html>
<html>
<head>
<title>HTML defer attribute example</title>
<style>
.mydiv {
border: 2px solid black;
text-align: center;
padding: 30px;
background: rgb(100, 100, 100, 0.4);
}
</style>
<script src="myheavyscript.js"></script>
</head>
<body>
<h3>HTML defer attribute example</h3>
<p>The defer attribute is used to executed only after the HTML document has been completely loaded.</p>
<div id="sample" class="mydiv">
<h1>This is a blocking code example.</h1>
<p>If the script appears before other DOM elements, the script without the defer attribute is executed before
the HTML document is fully loaded.</p>
</div>
</body>
</html>
Click on the "Try it Now" button to see how it works.
Example (Non-blocking)
<!DOCTYPE html>
<html>
<head>
<title>HTML defer attribute example</title>
<style>
.mydiv {
border:2px solid black;
text-align: center;
padding: 30px;
background: rgb(100, 100, 100, 0.4);
}
</style>
<script src="myheavyscript.js" defer></script>
</head>
<body>
<h3>HTML defer attribute example</h3>
<p>The defer attribute is used to executed only after the HTML document has been completely loaded.</p>
<div id="sample" class="mydiv">
<h1>This is a non-blocking code example.</h1>
<p>The script with the defer attribute is executed only after the HTML document is fully loaded, even though the script appears before other DOM elements.</p>
</div>
</body>
</html>
Click on the "Try it Now" button to see how it works.