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.
Code
// 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,windowexist 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.