跨浏览器且纯JavaScript检测document是否加载完成的方法是使用readyState.

1
2
3
if (document.readyState === 'complete') {
// 页面已完全加载
}

这样可以在document完全加载时监测到……

1
2
3
4
5
6
let stateCheck = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(stateCheck);
// document ready
}
}, 100);

或者使用onreadystatechange

1
2
3
4
5
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
// document ready
}
};

使用document.readyState === 'interactive'监听DOM是否加载完成。