Javascript on page loaded event

JavaScript Page Load Events

Summary: in this tutorial, you will learn about the events that are related to the page load including DOMContentLoaded , load , beforeunload , and unload .

Overview of JavaScript page load events

When you open a page, the following events occur in sequence:

  • DOMContentLoaded – the browser fully loaded HTML and completed building the DOM tree. However, it hasn’t loaded external resources like stylesheets and images. In this event, you can start selecting DOM nodes or initialize the interface.
  • load – the browser fully loaded the HTML and also external resources like images and stylesheets.

When you leave the page, the following events fire in sequence:

  • beforeunload – fires before the page and resources are unloaded. You can use this event to show a confirmation dialog to confirm if you really want to leave the page. By doing this, you can prevent data loss in case you are filling out a form and accidentally click a link to navigate to another page.
  • unload – fires when the page has completely unloaded. You can use this event to send the analytic data or to clean up resources.

Handling JavaScript page load events

To handle the page events, you can call the addEventListener() method on the document object:

document.addEventListener('DOMContentLoaded',() => < // handle DOMContentLoaded event >); document.addEventListener('load',() => < // handle load event >); document.addEventListener('beforeunload',() => < // handle beforeunload event >); document.addEventListener('unload',() => < // handle unload event >); Code language: JavaScript (javascript)

The following example illustrates how to handle the page load events:

html> html> head> title>JS Page Load Events title> head> body> script> addEventListener('DOMContentLoaded', (event) => < console.log('The DOM is fully loaded.'); >); addEventListener('load', (event) => < console.log('The page is fully loaded.'); >); addEventListener('beforeunload', (event) => < // show the confirmation dialog event.preventDefault(); // Google Chrome requires returnValue to be set. event.returnValue = ''; >); addEventListener('unload', (event) => < // send analytic data >); script> body> html>Code language: HTML, XML (xml)

Источник

Читайте также:  Отображение символов для html

Window: load event

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

This event is not cancelable and does not bubble.

Note: All events named load will not propagate to Window , even with bubbles initialized to true . To catch load events on the window , that load event must be dispatched directly to the window .

Note: The load event that is dispatched when the main document has loaded is dispatched on the window , but has two mutated properties: target is document , and path is undefined . These two properties are mutated due to legacy conformance.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("load", (event) => >); onload = (event) => >; 

Event type

Examples

Log a message when the page is fully loaded:

.addEventListener("load", (event) =>  console.log("page is fully loaded"); >); 

The same, but using the onload event handler property:

.onload = (event) =>  console.log("page is fully loaded"); >; 

Live example

HTML

div class="controls"> button id="reload" type="button">Reloadbutton> 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> 
body  display: grid; grid-template-areas: "control log"; > .controls  grid-area: control; display: flex; align-items: center; justify-content: center; > .event-log  grid-area: log; > .event-log-contents  resize: none; > label, button  display: block; > #reload  height: 2rem; > 

JavaScript

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`; >); 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Window: DOMContentLoaded event

The DOMContentLoaded event fires when the HTML document has been completely parsed, and all deferred scripts ( and ) have downloaded and executed. It doesn’t wait for other things like images, subframes, and async scripts to finish loading.

DOMContentLoaded does not wait for stylesheets to load, however deferred scripts do wait for stylesheets, and the DOMContentLoaded event is queued after deferred scripts. Also, scripts which aren’t deferred or async (e.g. ) will wait for already-parsed stylesheets to load.

The original target for this event is the Document that has loaded. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Document: DOMContentLoaded event.

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.

This event is not cancelable.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("DOMContentLoaded", (event) => >); onDOMContentLoaded = (event) => >; 

Источник

Оцените статью