Home  >  Article  >  Web Front-end  >  Events and sequence triggered when page loads

Events and sequence triggered when page loads

一个新手
一个新手Original
2017-10-14 10:25:433992browse

Foreword

When the page is loaded, it can be roughly divided into the following steps:

  1. Start parsing the HTML document structure

  2. Loading external style sheets and JavaScript scripts

  3. Parsing and executing JavaScript scripts

  4. DOM tree rendering completed

  5. Loading unfinished external resources (such as pictures)

  6. The page is loaded successfully

So what are triggered in the whole processWhat about the commonly used events?

document readystatechange event

 readyState The attribute describes the loading status of the document. Document.readyState will continue to change during the entire loading process, and each change will trigger the readystatechange event.

 readyState has the following status:

  Loading / Loading document is still loading.

Interactive / The interactive document has completed loading and the document has been parsed, but sub-resources such as images, stylesheets and frames are still loading.

Complete / Complete T document and all sub-resources have been loaded. The status indicates that the load event is about to be triggered.

For example, in step 2 corresponding to interactive and after step 5 corresponding to complete, the readystatechange event will be triggered.

PS: readyState and XMLHttpRequest.readyState when loading documents, images, etc. are different. Pay attention to distinguish

document DOMContentLoaded event

The DOMContentLoaded event is triggered when the DOM tree rendering is completed. At this time, external resources may still be loading. The ready event in jquery has the same effect

window load event

When all resources are loaded, the load event of the window will be triggered.

The load event of document cannot be triggered, but there is this event on MDN? Ask God for guidance! ! !

Example


  

测试页面加载时,事件触发次序

测试页面加载时,事件触发次序

测试页面加载时,事件触发次序

The log output in chrome is as follows:

resolve body JavaScript --> document interactive --> document DOMContentLoaded --> document complete --> window load

Exactly as expected. Therefore, scripts that only need the document structure to be loaded before they can be executed can monitor DOMContentLoaded; scripts that need all content to be loaded before they can be executed should monitor window.onload or document.readyState === 'complete'.

The above is the detailed content of Events and sequence triggered when page loads. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn