Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to define that the script is executed when the page has finished parsing ?

  • Last Updated : 24 Apr, 2021

In this article, we will get to know how to execute a script after a page has been finished parsing.

When you include any external script using the <script> tag you have an option to make the script load and execute after the HTML page has been finished loading and to achieve this you can use the defer keyword as an attribute in the script tag. This is useful when you’re including any huge external script that might block the UI rendering of the page, by using the defer attribute in the script tag you can load the HTML first, and when the UI rendering finishes the huge script will start executing.

The defer is a boolean attribute. It loads the script asynchronously and executes it after the HTML has been loaded. The defer keyword should be used only with external scripts means the src attribute should present. It loads the script when the DOM is content is ready, but before DOMContentLoaded has fired.

The scripts that are included using the defer keywords are called the deferred scripts.

Syntax:



<script src="example.js" defer></script>

Example:

In this example, we are including a heavy script (jQuery script) and showing how the two outputs are different. Here you can see in the first output we are not using the defer keyword and in the second output, we are using the defer keyword. 

HTML




<!DOCTYPE html>
<html>
<body>
    <p>Content before script</p>
    <script defer 
            src=
    </script>
  <p>Content after script</p>
    <button onclick="window.location.reload()">
        Refresh
    </button>
</body>
  
</html>

Output: 

  • Output without defer (The second <p> is being loaded after the script loaded fully)
  • Output with defer (The script is gets loaded after the DOM content loaded fully)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!