DOMContentLoaded 与 window.onload $(document).ready 的区别

window.onload是页面上所有资源加载完

 

 

DOMContentLoaded是HTML被parse完

(如果页面中有一个外引 async script和一个外引css,那么当HTML被parse完,这个事件就被触发了、这个css可能刚开始下载,js也可能刚开始下载)

(如果页面中有一个外引 同步 script和一个外引css,那么执行到script的时候,会卡住DOM的构建,由于script可以操作css,这时script也会阻塞住,等待CSS同步获取完成,然后进行script执行,最后触发DomContentLoaded)

 

 

$(document).ready 是为了解决兼容问题,jquery实现的一个模拟DOMContentLoaded功能的API,

比如在IE8中,可以用过document.readstatechange的状态监听DOM加载完成,跟高的ie中可以通过

document.documentElement.doScroll('left')(因为这个代码在DOM加载完前会抛出错误)

 

 

资料:

https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp

https://stackoverflow.com/questions/44920009/misconception-of-domcontentloaded-event

posted @ 2020-06-15 11:32  hh9515  阅读(215)  评论(1编辑  收藏  举报