Skip to content
jshacks.dev
Browser

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.

1 min read
Summarize in AI

People write DOMContentLoaded and expect the page to be fully ready, then measure an image and get zero. The two events mark different moments.

ready-events.jsJavaScript
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}`);
});
Text
DOMContentLoaded, image complete: false
load, image complete: true

DOMContentLoaded 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.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.