网页加载进度条
2021.03.24 Wed

document.readyState 属性描述了文档的加载状态,发生变化时,会在 document 对象上触发 readyStateChange 事件。
document.readyState 有三种状态,loading、interactive、complete

  • loading document 仍在加载
  • interactive 文档已被解析,"正在加载"状态结束,但是诸如图像,样式表和框架之类的子资源仍在加载。
  • complete 文档和所有子资源已完成加载。表示 load 状态的事件即将被触发。

DOMContentLoaded 与 load 事件:

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

1
2
3
4
5
6
7
8
9
10
11
window.addEventListener('load', (event) => {
console.log('load');
});

document.addEventListener('readystatechange', (event) => {
console.log(document.readyState);
});

document.addEventListener('DOMContentLoaded', (event) => {
console.log('COMContentLoaded');
});

运行结果:
interactive COMContentLoaded complete load

于是可以根据文档的加载属性 document.readyState 捕捉到不同的加载状态来设置加载动画。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
document.onreadystatechange = () => {
const headBar = document.querySelector('.header-bar');
headBar.style.background = 'lightblue';
if (document.readyState == 'interactive') {
headBar.style.transition = 'width 1.4s ease-in-out';
headBar.style.width = '67%';
}
if (document.readyState == 'complete') {
headBar.style.transition = 'width 0.3s ease-in-out';
headBar.style.width = '100%';
setTimeout(() => {
headBar.setAttribute('style', "transition:width 0s;width:0;background:''");
}, 500);
}
};

检测到页面内容有更新,是否刷新页面