DOMContentLoaded event

Definition

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.

A different event, load , should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate.

Synchronous JavaScript pauses parsing of the DOM.

If you want the DOM to get parsed as fast as possible after the user has requested the page, you can make your JavaScript asynchronous and optimize loading of stylesheets.

If loaded as usual, stylesheets slow down DOM parsing as they’re loaded in parallel, “stealing” traffic from the main HTML document.

Définition en français

L’évènement DOMContentLoaded est déclenché quand le document HTML initiale est complètement chargé et analysé, sans attendre la fin du chargement des feuilles de styles, images et sous-document.

Un évènement différent, load doit être utilisé pour détecter que la page entière est chargée. On utilise couramment à tord load là où DOMContentLoaded serait plus approprié.

Du code JavaScript synchrone va mettre en pause la création du DOM.

Si vous voulez charger le DOM le plus rapidement possible, vous pouvez faire votre code (en) JavaScript asynchrone et (en) optimiser le chargement des feuilles de styles.

Si vous chargez comme d’habitude, les feuilles de styles vont ralentir la création du DOM comme si elles étaient chargées en parallèle, en «volant» le trafic du document principale HTML.

Définition https://javascript.info

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 <img> and stylesheets may be not yet loaded.

  • load – not only HTML is loaded, but also all the external resources: images, styles, iframes 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, iframes, 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.

Examples

Basic usage

document.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
});