资源加载常常会导致页面的卡顿,我们可以每次执行的时候询问是否有执行时间再进行操作或者加载数据,示例代码如下
class splitLoader {
constructor(datas, consumer, hz) {
this.datas = datas;//按需加载的数据
this.consumer = consumer;//数据处理的回调
this.length = datas.length;
this.index = 0;
this.rate = Math.floor(1000 / (!hz ? 60 : hz));//hz,需要适配的显示器刷新率,默认60
}
run = () => {
if (this.index === this.length) {
return;
}
this.chunkSplitor(async (hastime) => {
const now = Date.now();
while (hastime(Date.now() - now) && this.index < this.length) {//执行时间和初始时间比较。
const item = this.datas[this.index];
await this.consumer(item, this.index);//需要执行的回调,这边把item和index都传出去了
this.index++;
}
this.run();
});
};
chunkSplitor = (task) => {//分割器,判断任务执行的时间是否小于刷新率的间隔时间,是则执行任务
setTimeout(() => {
task((time) => {
return time < this.rate;
});
}, this.rate);
};
}
//测试数据,生成50万条dom无卡顿感知,正常生成大概卡顿十多秒
const div = document.getElementById('app');
const imgLoad = new splitLoader(Array(500000).fill(1), (item, index) => {
const dd = document.createElement('span');
dd.innerHTML = item;
div.appendChild(dd);
}, 144);
imgLoad.run()
/*
const div = document.getElementById('app');
for(let i = 0;i<500000;i++){
const dd = document.createElement('span');
dd.innerHTML = i;
div.appendChild(dd);
}
*/
对您有帮助的话还请点个赞