图片异步加载的几种实现方案

2年前 (2022) 程序员胖胖胖虎阿
376 0 0

一. 异步串行加载

要求图片依次加载(上一张加载完成,再加载下一张)

const imgs = [url1, url2, url3,...];

1. ES5--递归方法

function loadImage() {
  const image = new Image();
  const itemUrlImage = imgs.shift();
  if (itemUrlImage) {
    image.src = itemUrlImage;  
    image.onload = function() {
      document.body.appendChild(image);
      loadImage();
    }
  }   
}
loadImage(); 

2. ES6--Promise对象

function loadByPromise() {
  let promise = function(url) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.src = url;
      image.onload = function() {
        document.body.appendChild(image);
        resolve('ok');
      }        
    })      
  }
  let p = Promise.resolve();
  for(let url of imgs) {
    p = p.then(() => promise(url))
  }
  p.catch(() => {}).then(() => {
    console.log("加载完成");
  })
}
loadByPromise();

3.ES6--async函数

async function loadAsync() {
  let promise = function(url) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.src = url;
      image.onload = function() {
        document.body.appendChild(image);
        resolve('ok');
      }        
    })      
  }
  for(let url of imgs) {
    await promise(url);
  }
}
loadAsync();

 二. 异步并行加载

要求图片并行加载,全部加载完成后,再插入DOM。

const imgs = [url1, url2, url3,...];

1. async函数

async function loadAsync() {
  let promise = function(url) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.src = url;
      image.onload = function() {
        resolve(image);
      }        
    })      
  }
  const promises = imgs.map(i => promise(i)); //实现并行加载
  let results = [];
  for(let promise of promises) {
    results.push(await promise);  //等待加载完成
  }
  results.forEach(image => {
    document.body.appendChild(image);
  })
}
loadAsync();

2.async函数+Promise.all

async function loadAsync() {
  let promise = function(url) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.src = url;
      image.onload = function() {
        resolve(image);
      }        
    })      
  }
  const promises = imgs.map(i => promise(i)); //实现并行加载
  const results = await Promise.all(promises);
  results.forEach(image => {
    document.body.appendChild(image)
  });
}
loadAsync();

 

版权声明:程序员胖胖胖虎阿 发表于 2022年11月3日 下午8:00。
转载请注明:图片异步加载的几种实现方案 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...