Window/document events

11.18

window 对象上有一些全局事件,会在页面加载和卸载的特定阶段触发。

DOMContentLoaded

  • 触发条件:初始 HTML document 完全加载和解析,不包括样式、图片和 subframes 等资源
  • 触发对象:window 或 document

同步的 JavaScript 会阻塞 DOM 的解析。样式虽然是异步加载,但也会占用一定的流量,从而拖慢页面加载。

可以通过异步加载 JavaScript 和优化样式加载来提升页面加载速度。

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

// The synchronous script is going to delay parsing of the DOM,
// so the DOMContentLoaded event is going to launch later.
for (let i = 0; i < 1000000000; i++) {
}

load

  • 触发条件:整个页面完全加载和解析,包括样式和图片等资源
  • 触发对象:window
window.addEventListener('load', function (event) {
  console.log('Page is fully loaded.')
})

load总是在DOMContentLoaded之后触发

document.readyState

描述了页面的加载状态。当值变化时,readystatechange事件会触发。

  • loading

    The document is loading

  • interactive

    The document has finished laoding and has been parsed. But sub-resources such as images, stylesheets and frames are still loading.

  • complete

    The document and all sub-resources have finished loading. The load event is about to fire

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

console.log(`readystate: ${document.readyState}`)
document.addEventListener('readystatechange', function (event) {
  console.log(`readystate: ${document.readyState}`)
})

window.addEventListener('load', function (event) {
  console.log('Page is fully loaded.')
})

// readystate: loading
// readystate: interactive
// DOM fully loaded and parsed.
// readystate: complete
// Page is fully loaded.

Others

  • beforeunload
  • unload
📖