javascript
  1. javascript-domcontentloaded

JavaScript DOMContentLoaded

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. It allows JavaScript to run only after the page is completely loaded, avoiding potential errors and issues.

Syntax

The syntax for adding a DOMContentLoaded event listener in JavaScript is as follows:

document.addEventListener('DOMContentLoaded', function() {
  // code to be executed after the document has been completely loaded
});

Example

<!DOCTYPE html>
<html>
<head>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      alert('DOM Ready!');
    });
  </script>
</head>
<body>
  <h1>Hello World!</h1>
  <p>This is some sample text</p>
</body>
</html>

Output

The above example displays an alert message saying "DOM Ready!" as soon as the page is fully loaded.

Explanation

HTML documents are parsed from top to bottom, so scripts that are placed at the top of the document can fire before the page has finished loading. This can lead to unexpected behavior or errors - for example, if a script tries to access an element that hasn't finished loading yet.

The DOMContentLoaded event fires when the HTML document has been fully loaded and parsed, including any linked scripts and stylesheets. It signals that the document is now ready to be manipulated by JavaScript.

Use

The DOMContentLoaded event is commonly used to initialize JavaScript code on the page. Any code that manipulates the DOM or interacts with user input should be placed inside a DOMContentLoaded event listener.

Important Points

  • The DOMContentLoaded event is fired only once, when the initial HTML document has been completely loaded.
  • It is different from the window.onload event, which fires when all the page's content - including images, scripts, and subframes - has finished loading.
  • It is recommended to use the DOMContentLoaded event instead of placing scripts at the top of the page or in the head section.

Summary

The DOMContentLoaded event is a useful JavaScript event that fires when the initial HTML document has been fully loaded and parsed. It allows JavaScript code to run only after the page is completely loaded, avoiding potential errors and issues. Developers can use it to initialize JavaScript code on the page, ensuring that it can interact with user input and manipulate the DOM without any problems.

Published on: