Javascript document content loaded

DOMContentLoaded

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

Note: There are also plenty of general-purpose and standalone libraries that offer cross-browser methods to detect that the DOM is ready.

Speeding up

If you want the DOM to get parsed as fast as possible after the user has requested the page, you could 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.

General info

Specification HTML5 Interface Event Bubbles Yes Cancelable Yes (although specified as a simple event that isn’t cancelable) Target Document Default Action None.

Properties

Property Type Description
target Read only EventTarget The event target (the topmost target in the DOM tree).
type Read only DOMString The type of event.
bubbles Read only Boolean Whether the event normally bubbles or not.
cancelable Read only Boolean Whether the event is cancellable or not.

Example

  
  
function doSomething() < console.info("DOM loaded"); >// `DOMContentLoaded` may fire before your script has a chance to run, so check before adding a listener if (document.readyState === "loading") < document.addEventListener("DOMContentLoaded", doSomething); >else < // `DOMContentLoaded` already fired doSomething(); >

Specifications

Browser compatibility

We’re converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven’t yet converted the data it contains. Find out how you can help!

Читайте также:  Html js ajax примеры
Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1.0 [1] (Yes) 1.0 (1.7 or earlier) [1] 9.0 [2] 9.0 3.1 [1]
Feature Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) [1] (Yes) 1.0 (1) [1] ? [2] (Yes) (Yes) [1]
[1] Bubbling for this event is supported by at least Gecko 1.9.2, Chrome 6, and Safari 4. [2] Internet Explorer 8 supports the readystatechange event, which can be used to detect when the DOM is ready. In earlier versions of Internet Explorer, this state can be detected by repeatedly trying to execute document.documentElement.doScroll(«left»); , as this snippet will throw an error until the DOM is ready.

Источник

DOM Content Loaded

Событие DOM Content Loaded происходит, когда браузер разобрал HTML-страницу и составил DOM-дерево. Если нужно, чтобы страница обязательно загрузилась полностью, лучше присмотреться к load .

Как пишется

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

 document.addEventListener('DOMContentLoaded', function ()  console.log('DOM готов!')>) document.addEventListener('DOMContentLoaded', function ()  console.log('DOM готов!') >)      

Как понять

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

Чтобы показать пользователю страницу, браузер делает следующие первые шаги:

  1. Запрашивает HTML-страницу с сервера;
  2. Затем обрабатывает полученный HTML и создаёт DOM для взаимодействия между JavaScript и HTML (☝️ в конце этого этапа происходит событие DOM Content Loaded ).

Событие DOM Content Loaded происходит раньше события load и гарантирует, что DOM готов. Можно искать по нему узлы и не бояться, что что-то не догрузилось (кроме стилей, картинок и так далее).

На практике

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

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

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

🛠 Основной сценарий использования DOM Content Loaded : инициализация интерфейса и первые обращения к серверу.

🛠 Нормальной практикой считается запуск всего приложения в момент срабатывания DOM Content Loaded , таким образом исключается случай, когда DOM ещё не догрузился, а приложение уже ищет по нему узлы.

Источник

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

Источник

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