js判断多个请求加载完毕

通过js判断多个请求是否加载完毕

判断下面3张图片是否全部加载完毕

var imgStr = [
'https://img10.360buyimg.com/da/jfs/t14395/79/2162545826/196335/87c2c3f2/5a718ab1N5fa358da.jpg',
'https://img10.360buyimg.com/da/jfs/t15181/264/2141469177/100278/a325be09/5a7134eaNd79570bc.jpg',
'https://m.360buyimg.com/babel/jfs/t19699/281/383788365/50387/1ddabaee/5a719ce8Nee5a9273.jpg'
]


通过比较传统的方式实现

var img = [],
    flag = 0;
for(var i = 0, len = imgStr.length; i < len; i++) {
  img[i] = new Image();
  img[i].src = imgStr[i];
  img[i].onload = function() {
    flag++
    if(flag === imgStr.length) {
        console.log('已全部加载完毕')  
    }
  }
}


通过Promise方式实现

 let imgLoadAll = [], img = [];
 for(let i = 0, len = imgStr.length; i < len; i++) {
     imgLoadAll[i] = new Promise((resolve, reject)=>{
         img[i] = new Image()
         img[i].src = imgStr[i]
         img[i].onload = function() {
            resolve(img[i])
         }
         img[i].onerror = function() {
            reject(img[i])
         }
     })
 }

// 第一张图加载完毕
imgLoadAll[0].then((img) => {
  console.log('第一张图加载完毕')
}).catch((img)=> {
  console.log('第一张图加载失败')
})

// 全部加载完毕
Promise.all(imgLoadAll).then((img) => {
  console.log('全部加载完毕')
}).catch((img)=> {
  console.log('全部加载失败')
})

你可能感兴趣的:(js判断多个请求加载完毕)