Why DOMContentLoaded can fire before images load
Why DOMContentLoaded fires before images finish loading, and how it differs from the load event, which waits for images, frames and stylesheets.
People write DOMContentLoaded and expect the page to be fully ready, then measure an image and get zero. The two events mark different moments.
document.addEventListener('DOMContentLoaded', () => {
const img = document.querySelector('img');
console.log(`DOMContentLoaded, image complete: ${img.complete}`);
});
window.addEventListener('load', () => {
const img = document.querySelector('img');
console.log(`load, image complete: ${img.complete}`);
});DOMContentLoaded, image complete: false
load, image complete: trueDOMContentLoaded fires on document once the HTML has been parsed and deferred scripts have run. It does not wait for images, subframes or async scripts. load fires on window after those subresources finished. A script that must wait for a stylesheet is held by the browser, so such stylesheets do delay DOMContentLoaded. The order is defined in the HTML Standard.
If your code only needs the DOM, a script with defer or type="module" already runs at the right time and needs no listener. For image sizes, use img.decode() or the image's own load event, or set width and height in the markup. If the script loads late, document.readyState is already interactive or complete, and the listener would never fire.