Back to Home

Page: DOMContentLoaded, load, beforeunload, unload

The lifecycle of an HTML page has three important events: - DOMContentLoaded – the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures and stylesheets may not yet have loaded. - load – not only HTML is loaded, but also all the external resources: images, styles etc. - beforeunload/unload – the user is leaving the page. Each event may be useful: - DOMContentLoaded event – DOM is ready, so the handler can lookup DOM nodes, initialize the interface. - load event – external resources are loaded, so styles are applied, image sizes are known etc. - beforeunload event – the user is leaving: we can check if the user saved the changes and ask them whether they really want to leave. - unload – the user almost left, but we still can initiate some operations, such as sending out statistics. Let’s explore the details of these events.

DOMContentLoaded

The DOMContentLoaded event happens on the document object. We must use addEventListener to catch it: For instance: In the example, the DOMContentLoaded handler runs when the document is loaded, so it can see all the elements, including below. But it doesn’t wait for the image to load. So alert shows zero sizes. At first sight, the DOMContentLoaded event is very simple. The DOM tree is ready – here’s the event. There are few peculiarities though.

DOMContentLoaded and scripts

When the browser processes an HTML-document and comes across a or block DOMContentLoaded, the browser waits for them to execute. - Images and other resources may also still continue loading. - The load event on window triggers when the page and all resources are loaded. We rarely use it, because there’s usually no need to wait for so long. - The beforeunload event on window triggers when the user wants to leave the page. If we cancel the event, browser asks whether the user really wants to leave (e.g we have unsaved changes). - The unload event on window triggers when the user is finally leaving, in the handler we can only do simple things that do not involve delays or asking a user. Because of that limitation, it’s rarely used. We can send out a network request with navigator.sendBeacon. - document.readyState is the current state of the document, changes can be tracked in the readystatechange event: - loading – the document is loading. - interactive – the document is parsed, happens at about the same time as DOMContentLoaded, but before it. - complete – the document and resources are loaded, happens at about the same time as window.onload, but before it.

document.addEventListener("DOMContentLoaded", ready);
// not "document.onDOMContentLoaded = ..."
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: dom