renjar
7/15/2018 - 4:03 AM

preloadImgs

图片同步或异步预加载

const preloadImgs = (imgs = [], async = true) => {
  const len = imgs.length;
  let count = 0;
  
  const syncLoad = () => {
    const oImg = new Image();
    oImg.onload = oImg.onerror = () => {
      if (count >= len) {
        // 下载完成
        
      } else {
        // 继续下载
        syncLoad();
      }
      count++;
    }
    oImg.src = imgs[count];
  }
  
  const asyncLoad = () => {
    imgs.forEach(img => {
      const oImg = new Image();
      oImg.onload = oImg.onerror = () => {
        count++;
      }
      oImg.src = img;
    });
    
    if (count >= len) {
      // 下载完成
    }
  }
  
  async ? asyncLoad() : syncLoad();

}