Wednesday, September 25, 2024
Google search engine
HomeLanguagesJavascriptHow to define that the script is executed when the page has...

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

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)
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments