Difference between DOMContentLoaded and load Events

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.