What is the load event used for?
JavaScriptThe short answer
The load event fires when a resource has finished loading. On window, it fires when the entire page (HTML, CSS, images, fonts) is fully loaded. On individual elements like <img> or <script>, it fires when that specific resource finishes loading. It is used to run code that depends on all resources being ready.
Window load event
window.addEventListener('load', () => { // Everything is fully loaded — HTML, images, stylesheets, fonts console.log('Page fully loaded'); // Safe to read image dimensions const img = document.querySelector('img'); console.log(img.naturalWidth, img.naturalHeight);});Image load event
const img = new Image();img.addEventListener('load', () => { console.log('Image loaded:', img.width, img.height); document.body.appendChild(img);});img.addEventListener('error', () => { console.log('Image failed to load');});img.src = 'photo.jpg';Script load event
const script = document.createElement('script');script.addEventListener('load', () => { console.log('Script loaded and ready');});script.src = 'https://cdn.example.com/library.js';document.head.appendChild(script);load vs DOMContentLoaded
- DOMContentLoaded — fires when HTML is parsed (images may still be loading)
- load — fires when everything is fully loaded
For most cases, DOMContentLoaded is what you want because you rarely need to wait for all images. Use load only when you need fully loaded resources (like reading image dimensions).
Common use cases
- Reading image dimensions after they load
- Hiding a loading spinner after everything is ready
- Running code that depends on external scripts or stylesheets
- Measuring page load performance
Interview Tip
Explain the difference between load and DOMContentLoaded — this is the most common follow-up. DOMContentLoaded waits for HTML only, load waits for everything. For most cases, DOMContentLoaded (or defer scripts) is preferred.
Why interviewers ask this
This tests basic browser event knowledge. Interviewers want to see if you know when different events fire during page loading and which one to use for different scenarios.