分割加载器

资源加载常常会导致页面的卡顿,我们可以每次执行的时候询问是否有执行时间再进行操作或者加载数据,示例代码如下

    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);
}

*/

对您有帮助的话还请点个赞

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值