The DOMContentLoaded event in JavaScript is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This event is useful for executing JavaScript code as soon as the DOM is ready to be manipulated.
Here’s how it works:
-
Event Listener: You can add an event listener for
DOMContentLoadedto execute a function when the event occurs. -
Execution Timing: The code inside the event listener will run as soon as the DOM is fully loaded, allowing you to safely manipulate elements.
Example:
document.addEventListener('DOMContentLoaded', function() {
// Your code here
console.log('DOM fully loaded and parsed');
// You can manipulate DOM elements here
});
Key Points:
- The
DOMContentLoadedevent does not wait for stylesheets, images, or other resources to load. - It is different from the
loadevent, which waits for all resources to finish loading.
Using DOMContentLoaded is a common practice to ensure that your scripts run at the right time, improving the performance and user experience of your web applications.
