w3resource

HTML5: How to specify that the script is executed when the page has finished parsing?

Go to Exercise page

Solution:

HTML Code:

<!DOCTYPE html><!-- Define document type as HTML5 -->
<html><!-- Start of HTML document -->
<head><!-- Start of head section -->
<meta charset="utf-8"><!-- Define character encoding -->
<title>How to specify that the script is executed when the page has finished parsing</title><!-- Title of the document -->
</head><!-- End of head section -->
<body><!-- Start of body section -->
<script src="https://www.w3resource.com
/html-css-exercise/basic/solution/async-example.js" defer></script><!-- Include an external script with defer attribute -->
<p>The script above requests information from the paragraph below. Normally, this is not possible, because the script is executed before the paragraph exists.</p><!-- Text providing explanation of script behavior -->
<p id="output">Click Me</p><!-- Define a paragraph with an id for interaction -->
</body><!-- End of body section -->
</html><!-- End of HTML document -->


Explanation:

  • This HTML code demonstrates how to specify that a script is executed when the page has finished parsing using the defer attribute.
  • The <script> element is used to include an external JavaScript file indicated by the src attribute.
  • The src attribute points to the URL of the external script file, "https://www.w3resource.com/html-css-exercise/basic/solution/async-example.js".
  • By adding the defer attribute to the <script> element, the script is deferred, meaning it is executed after the HTML document has been fully parsed.
  • The script will not block the parsing of the HTML document, allowing the HTML elements to be fully loaded before the script is executed.
  • This behavior ensures that the script does not interfere with the loading and rendering of HTML content, improving page performance and user experience.
  • The text following the script explains its purpose, demonstrating that the script requests information from a paragraph that follows it, and emphasizes that this would normally not be possible without using defer.

Live Demo:

See the Pen script-defer-answer by w3resource (@w3resource) on CodePen.


See the solution in the browser

Supported browser

Firefox logo Chrome logo Opera logo Safari logo Internet Explorer logo
Yes Yes Yes Yes Yes

Go to Exercise page

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/html-css-exercise/basic/script-defer-answer.php