DOMContentLoaded Fires Before load

DOMContentLoaded marks a parsed DOM while load waits for every subresource; late scripts guard on readyState instead of assuming the phase.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
// readyState tells which phase the document is in right now
console.log('current readyState:', document.readyState);

// DOMContentLoaded: DOM parsed, images and stylesheets may still be loading
document.addEventListener('DOMContentLoaded', () => {
  console.log('dom ready:', document.readyState);
});

// load: every subresource finished; old scripts use it as a single hook
window.addEventListener('load', () => {
  console.log('fully loaded:', document.readyState);
});

// Scripts that run late must not assume the phase — guard on readyState
if (document.readyState !== 'loading') {
  console.log('dom already parseable, init now');
} else {
  document.addEventListener('DOMContentLoaded', () => console.log('init after parse'));
}

Watch out for

  • No third-party code is loaded at any point while this runs.
  • document, window exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

The demo output is labeled (current readyState:, dom ready:, fully loaded:), so every line of output can be traced to the operation that made it.

Statements that matter

document.addEventListener('DOMContentLoaded', () => {
  console.log('dom ready:', document.readyState);
});
window.addEventListener('load', () => {
  console.log('fully loaded:', document.readyState);
});

Interactive Tools for This Topic

FAQ

Does DOMContentLoaded Fires Before load run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.