Skip to content
Related Articles

Related Articles

Improve Article
Difference between DOMContentLoaded and load Events
  • Last Updated : 18 Nov, 2019

These two events DOMContentLoaded and load are used to check when a webpage has loaded completely. Still, there are some factors that determine the preference of one over the other. Let’s have a look at both of them and understand their working.

DOMContentLoaded event gets executed once the basic HTML document is loaded and its parsing has taken place. This event doesn’t wait for the completion of the loading of add-ons such as stylesheets, sub-frames and images/pictures.

Syntax:

document.addEventListener("DOMContentLoaded", function(e) {
  console.log("GfG page has loaded");
});

Example 1:




<!DOCTYPE>
<html>
  
<head>
    <title>
        Output of DOMContentLoaded and Load events
    </title>
  
    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function(e) {
            console.log("GfG page has loaded");
        });
    </script>
</head>
  
<body>
    <img src=
         style="align-content: center">
</body>
  
</html>

Output:
Output



Here in the output, it can be seen that the console log window displays the message, which signifies the completion of loading the DOM of the webpage.

Advantages of using DOMContentLoaded event:

  • It helps in improving user experience as it shows messages or content much faster.
  • It takes lesser time in loading the page.

load event performs its execution differently. This event gets completed once all the components i.e. DOM hierarchy along with associated features of a webpage such as CSS files, JavaScript files, images/pictures, and external links are loaded. So basically, the load event helps in knowing when the page has fully-loaded.

Syntax:

document.addEventListener("load", function(e) {
  console.log("The page has completely loaded.");
});

Example 2:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Output of DOMContentLoaded and Load events
    </title>
  
    <script type="text/javascript">
        document.addEventListener("load", function(e) {
            console.log("GfG page has loaded completely");
        });
    </script>
</head>
  
<body>
    <img src=
         style="align-content: center">
</body>
  
</html>

Output:
Output of load event

Advantages of using load event:

  • This event helps in knowing when all the components of the webpage is loaded.



My Personal Notes arrow_drop_up
Recommended Articles
Page :