w3resource

HTML5: How to specify that the script is executed asynchronously?

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 asynchronously</title><!-- Title of the document -->
</head><!-- End of head section -->
<body><!-- Start of body section -->
<p id="output">Click Me</p><!-- Define a paragraph with an id for interaction -->
<script 
src="https://www.w3resource.com/html-css-exercise/basic/solution/async-example.js"></script><!-- Include an external script with async attribute -->
</body><!-- End of body section -->
</html><!-- End of HTML document -->

Explanation:

  • This HTML code demonstrates how to specify that a script is executed asynchronously using the async 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 default, scripts included with the <script> element are executed synchronously, meaning the browser will pause parsing the HTML document to load and execute the script.
  • However, by adding the async attribute to the <script> element, the script is executed asynchronously, allowing the browser to continue parsing the HTML document while the script loads and executes in the background.
  • This can improve page loading performance, especially for scripts that are not critical for the initial rendering of the page.

Live Demo:

See the Pen script-async-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.



Follow us on Facebook and Twitter for latest update.