When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The load event happens when a resource or document finishes loading.
When load happens
A resource or document finishes loading.
You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.
A small working example
<img id="demo-target" alt="Sample photograph" width="240" height="160">
<p id="event-status" role="status">Waiting for load...</p>
<script>
const eventTarget = document.getElementById("demo-target");
const eventStatus = document.getElementById("event-status");
if (eventTarget) {
eventTarget.addEventListener("load", (eventDetails) => {
eventStatus.textContent = "load event received";
console.log(eventDetails.type, eventDetails.target);
});
}
eventTarget.src = "sample-photo.jpg";
</script>
Reading the code
The browser listens for load on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.
Provide a valid image and observe the successful load.
Try it in your browser
Open the page, show the Console panel, and follow this test: Provide a valid image and observe the successful load. Then change one thing in the example and observe whether the event still fires.
Common Beginner Mistakes
- Expecting
loadto fire without its required user action or browser condition. - Provide a valid image and observe the successful load.
- Adding repeated event listeners without considering cleanup or unwanted side effects.
Key Takeaways
loadreports a resource or document finishes loading.addEventListener("load", ...)listens for the event on the appropriate target.- Provide a valid image and observe the successful load.