ES6 - 通过Promise异步实现所有图片加载之后再添加到页面

{
  // add to page after all the imgs loaded

  function loadImg(src) {
    return new Promise((resolve,reject)=>{
      let img = document.createElement('img');
      img.src = src;
      img.onload = () => {
        resolve(img);
      };
      img.onerror = (err) => {
        reject(err)
      }
    })
  }

  function showImg(imgs) {
    imgs.forEach((img)=>{
      document.body.appendChild(img);
    })
  }

  Promise.all([
    loadImg('https://s1.51cto.com/images/201710/12/f822140cd581a82f0d8c94a8535f6f32.png'),
    loadImg('https://static1.51cto.com/edu/center/images/activity/20171111-rb.jpg'),
    loadImg('https://s2.51cto.com/wyfs02/M02/9E/61/wKiom1mP2HPzK45lAAAnawVQlAk105.gif')
  ]).then(showImg)
}

 

posted @ 2017-10-17 18:28  zhaoxingya  阅读(344)  评论(0编辑  收藏  举报