What is the DOMContentLoaded
event, and how does it work?
The DOMContentLoaded
event is fired when everything in the HTML document has been loaded and parsed. If you have external stylesheets, or images, the DOMContentLoaded
event will not wait for those to be loaded. It will only wait for the HTML to be loaded.
This differs from the load
event, which waits for everything to be loaded, including external stylesheets, images, and so on.
Here is the example syntax for using the DOMContentLoaded
event:
document.addEventListener("DOMContentLoaded", function () {
console.log("DOM is loaded.");
});
Once the DOM is loaded, the function will be executed and the message DOM is loaded.
will be logged to the console.
Now, let’s take a look at another example using the DOMContentLoaded
event. In this example, we have an image inside the HTML:
<h1>Image Change on DOM Loaded</h1>
<img
id="example-img"
src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg"
alt="Cat relaxing"
/>
To update the image, we can create a function that changes the src
attribute of the image:
function changeImg() {
const img = document.getElementById("example-img");
img.src =
"https://cdn.freecodecamp.org/curriculum/responsive-web-design-principles/FCCStickers-CamperBot200x200.jpg";
console.log("image was just changed");
}
We can then check if the DOM is still loading and add an event listener for the DOMContentLoaded
event. If the DOMContentLoaded
event has already fired, we can call the changeImg
function directly:
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", changeImg);
} else {
console.log("DOMContentLoaded has already fired");
changeImg();
}
If you were to run this code, and refresh the page, you would see the image change to the new image after the DOM has loaded. It happens pretty quickly, but you will see a slight flicker as the image changes.
The DOMContentLoaded
event is useful when you want to run some JavaScript code as soon as the DOM is loaded, but before all the external resources like images and stylesheets are loaded.