domcontentLoaded
DOMContentLoaded Event
The DOMContentLoaded event triggers once the HTML document is fully parsed and any deferred scripts have run. However, it does not wait for images, subframes, or asynchronous scripts to load. To detect when all resources, including images, are fully loaded, use the load event.
Syntax
<element DOMContentLoaded="script"></element>
Example
The example below listens for the DOMContentLoaded event and updates a <div> element as soon as the document is parsed—before the full page load completes.
<div class="controls">
<button id="reload" type="button">Reload</button>
</div>
<div class="event-log">
<label for="eventLog">Event log:</label>
<textarea
readonly
class="event-log-contents"
rows="8"
cols="30"
id="eventLog"></textarea>
</div>
const log = document.querySelector(".event-log-contents");
const reload = document.querySelector("#reload");
reload.addEventListener("click", () => {
log.textContent = "";
setTimeout(() => {
window.location.reload(true);
}, 200);
});
window.addEventListener("load", (event) => {
log.textContent += "load\n";
});
document.addEventListener("readystatechange", (event) => {
log.textContent += `readystate: ${document.readyState}\n`;
});
document.addEventListener("DOMContentLoaded", (event) => {
log.textContent += "DOMContentLoaded\n";
});
DOMContentLoaded fires compared to the full page load.Conclusion
The DOMContentLoaded event allows scripts to execute as soon as the HTML is parsed, without waiting for additional resources like images. This improves responsiveness and enhances webpage performance, making it a crucial event for optimizing user experience.
Document
HTML document event attributes manage user interactions and document-level events, such as loading, resizing, and clicking, to enhance page behavior and responsiveness.
onafterprint
The onafterprint event activates when a page begins printing or when the print dialog is closed. It is supported by most major browsers, but not by Internet Explorer or Edge.