How to execute a script asynchronously in HTML5 ?
In this article, we will learn how to execute a script asynchronously on a webpage. This can be used in situations where loading the content is important as heavy scripts can cause the page to wait for it to load thereby making the page appear incomplete. Asynchronously loading would solve this issue of blocking DOM rendering.
The script tag is used to implement external and external scripts inside the webpage. To make the scripts run asynchronously, we have two attributes, the first is async and the second is defer. These are boolean type attributes and both load scripts asynchronously without blocking the DOM rendering.
The main difference between the both is the async attributes asynchronously executes the script just after loading without waiting for the DOM to finish rendering but the defer attribute executes the script when the DOM content is fully loaded. The async attribute is not supported by the older browsers, but defer is supported by older browsers.
When async and defer are both used, then the defer attribute is ignored by the browser. However, if the browser is old and async is not supported then the defer attribute will work.
Example 1: In this example we have four elements, the first is a <p> element which is the content before the script, the second is the <script> element that contains the script to be loaded, the third is another <p> element which is the content after the script, and the fourth is the <button> element to refresh the page. We will be loading the script asynchronously and putting the script in the middle of the code to see if it is blocking the DOM rendering or not.
Without using the async attribute, the second <p> element loads after some time:
Using the async attribute, the script loads asynchronously without blocking the DOM rendering
Example 2: This example is the same as the previous one, however we are using defer instead of async. In this case, the script get loaded after all the DOM content is rendered.
Without using the defer attribute, the second <p> element loads after some time:
Using the defer attribute, the script loads after the DOM rendering finishes:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.