Html javascript document load

load

Событие load происходит, когда загрузилась и HTML страница (за это отвечает событие DOM Content Loaded ), и все ресурсы для её отображения пользователю: стили, картинки и другое.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Можно подписаться на объект window :

 window.addEventListener('load', function ()  console.log('Страница готова!')>) window.addEventListener('load', function ()  console.log('Страница готова!') >)      

Или поймать событие на элементах, у которых есть ресурс загрузки:

 const img = document.getElementById('img') img.addEventListener('load', function ()  alert('А вот и картиночка')>) const img = document.getElementById('img') img.addEventListener('load', function ()  alert('А вот и картиночка') >)      

Как понять

Скопировать ссылку «Как понять» Скопировано

Событие load гарантирует, что браузер отображает страницу полностью: все стили и картинки готовы, размеры элементов на странице посчитаны верно и доступны. Предшествующее load событие DOM Content Loaded таких гарантий не даёт. То же самое с отдельными элементами на странице: если случился load , значит элемент полностью загрузился.

Попробуйте открыть новую страничку кнопкой в демо:

 window.addEventListener('load', function ()  alert('Хоп! Страничка полностью загрузилась, поэтому стили радуют глаз!')>) window.addEventListener('load', function ()  alert('Хоп! Страничка полностью загрузилась, поэтому стили радуют глаз!') >)      

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 Чаще применяют DOM Content Loaded .

🛠 Событие load используется, когда код работает со стилями и другими параметрами отображения. Такой код нужен редко, поэтому и событие используется нечасто.

Источник

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.

Источник

Читайте также:  Карта-изображение
Оцените статью