Difference between document `load` event and document `DOMContentLoaded` event?
TL;DR
The DOMContentLoaded
event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The load
event, on the other hand, fires when the entire page, including all dependent resources such as stylesheets and images, has finished loading.
document.addEventListener('DOMContentLoaded', function () {console.log('DOM fully loaded and parsed');});window.addEventListener('load', function () {console.log('Page fully loaded');});
Difference between document load
event and document DOMContentLoaded
event
DOMContentLoaded
event
The DOMContentLoaded
event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This event is useful when you want to execute JavaScript code as soon as the DOM is ready, without waiting for all resources to be fully loaded.
document.addEventListener('DOMContentLoaded', function () {console.log('DOM fully loaded and parsed');});
load
event
The load
event is fired when the entire page, including all dependent resources such as stylesheets, images, and subframes, has finished loading. This event is useful when you need to perform actions that require all resources to be fully loaded, such as initializing a slideshow or performing layout calculations that depend on image sizes.
window.addEventListener('load', function () {console.log('Page fully loaded');});
Key differences
- Timing:
DOMContentLoaded
fires earlier thanload
.DOMContentLoaded
occurs after the HTML is fully parsed, whileload
waits for all resources to be loaded. - Use cases: Use
DOMContentLoaded
for tasks that only require the DOM to be ready, such as attaching event listeners or manipulating the DOM. Useload
for tasks that depend on all resources being fully loaded, such as image-dependent layout calculations.