The defer attribute is a Boolean value that signifies the execution of a script occurs once the document has been fully parsed. This attribute is applicable exclusively to external scripts (meaning it only functions when the src attribute is specified in the <script> tag). It indicates that the script will not generate any content, allowing the browser to proceed with parsing the remaining elements of the page. Consequently, the <script> that includes the defer attribute does not impede the loading of the page.
The application of the defer attribute can be illustrated through the image below:
This attribute tells the browser to execute the <script> file when the entire HTML document gets fully parsed. Sometimes, the application consumes more memory by adding the <script> tag in the HTML head section, and it also causes performance issues. To improve the performance, we can add the defer attribute in the <script> tag.
Occasionally, the script may require a longer loading duration than anticipated, resulting in a blank page being displayed rather than the intended content. This situation can be particularly problematic on mobile devices, which typically have limited memory capacity. To enhance loading performance, we can utilize the defer attribute.
The defer attribute is not supported in earlier versions of browsers; therefore, for those browsers, we need to implement an alternative method to achieve the same effect as the defer attribute. The alternative approach requires that we place the <script> section immediately before the </body> tag within the HTML document. This can be accomplished in the following manner:
<body>
<script src = "https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"> </script>
</body>
Syntax
<script defer>
Example
In this instance, we are utilizing an external JavaScript file named myscript.js.
<!DOCTYPE html>
<html>
<head>
<script src = "https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" defer>
</script>
</head>
<body>
<div>
<h1> logic-practice.com </h1>
<h3> This is an example of defer attribute. </h3>
</div>
</body>
</html>
myscript.js
alert(" Hello World. \n Welcome to the logic-practice.com \n This is an example of the defer attribute. ");
Output
Upon executing the code provided above, the resulting output will be -