What is the role of deferred scripts in JavaScript?
Answers (1)
Add AnswerThe defer is a Boolean value, used to indicate that script is executed after the document has been parsed. It works only with external scripts (i.e., works only when we are specifying the src attribute in <script> tag). It declares that the script will not create any content. So, the browser can continue the parsing of the rest of the page. The <script> with the defer attribute does not block the page.
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.
Sometimes the script takes more than expected loading time and displays a blank page instead of content. In 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.
The defer attribute is not allowed in older browsers, so for older browsers, we have to use the alternative of the defer attribute. The alternative solution is that we must have to specify the <script> section just before the </body> tag of HTML file. It can be done as follows:
<body> <script src = " "> </script> </body>
Syntax:
<script defer>
Example
Here, we are using an external javascript file, i.e., myscript.js.
<!DOCTYPE html> <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>
Output: