js多图预加载以及显示进度

实现方案

框架用的是vue,进度条用了下element的。 实现非常简单,以vue举例只需用到 percentage(进度)、progressShow(进度条显示控制)、imgList(原始图片数组)、readyImg(加载完成图片数组)四个参数。 在页面加载时调用图片预加载函数,并在单张加载完成时计算出进度在全部加载完成600毫秒后(为了让进度条走完)显示页面即可。 最后附上js代码

created部分

this.prestrain(
          this.imgList,
          // 单张加载完成
          (img) => {
          
   
            this.readyImg.push(img.src);
            this.percentage =
              (this.readyImg.length / this.imgList.length).toFixed(2) * 100;
          },
          // 全部加载完成
          () => {
          
   
            setTimeout(() => {
          
   
              this.progressShow = false;
            }, 600);
          }
        );

图片预加载函数

prestrain(imgList = [], underway, accomplish) {
          
   
          var loadImage = function (src) {
          
   
            return new Promise(function (resolve, reject) {
          
   
              let img = new Image();
              img.onload = function () {
          
   
                resolve(img); //加载时执行resolve函数
              };
              img.onerror = function () {
          
   
                reject(src + "这个地址错误"); //抛出异常时执行reject函数
              };
              img.src = src;
            });
          };
          function* fn() {
          
   
            for (let i = 0; i < imgList.length; i++) {
          
   
              yield loadImage(imgList[i]);
            }
          }
          let s = fn();
          let value = s.next().value;
          resume();
          function resume() {
          
   
            value.then((img) => {
          
   
              // 单张加载完成
              underway && underway(img);
              value = s.next().value;
              if (value) {
          
   
                resume();
              } else {
          
   
                // 全部加载完成
                accomplish && accomplish();
              }
            });
          }
        },
经验分享 程序员 微信小程序 职场和发展