JavaScript "defer" attribute

JavaScript "defer" attribute

·

2 min read

We all know the importance of performance and clean code in today's world thus, in this article I am going to explain an crucial attribute which only be used with the external script (i.e. works only when we specify the src attribute in <script>tag.

The defer is a Boolean value which indicates that the script is executed after the document has been parsed. It declares that the script will not create any content so that the browser can continue the parsing of the rest of the page. This attribute tells the browser to execute the <script> file when the entire HTML document gets fully parsed.

Sometimes the script takes more than expected loading time and displays the blank page instead of content which may cause performance issues specially for mobile devices, it will be a worse situation because of the low memory of small devices. So, by using the defer attribute, we can increase the loading performance.

See this for a pictorial view:

Syntax:

<script src = " " defer> </script>

Let see the example below to understand it more clearly:

<html>  
<head>  
<script src = "myscript.js" defer> </script>  

</head>  
<body>  
<div>  
<h1> javaTpoint.com </h1>  
<h3> This is an example of defer attribute.  </h3>  
</div>  
</body>  
</html>

The defer attribute is not allowed in older browsers so for this we can use an alternative solution which is use the <script tag just before the <body> tag of a HTML file