JS判断图片全部加载完成

2017-11-22  本文已影响0人  小白_pk
直接放代码了
<script language="javascript">
let mulitImg = [
    ... //图片路径列表
]
let promiseAll = [],
    img = [],
    imgTotal = mulitImg.length

for (let i = 0; i < imgTotal; i++) {
    promiseAll[i] = new Promise((resolve, reject) => {
        img[i] = new Image()
        img[i].src = mulitImg[i]
        img[i].onload = function() {
            console.log(`第${i}张加载完成`)
            resolve(img[i])
        }
        img[i].onerror = function(err) {
            //图片出错,设置默认地址
            this.src = "默认图片地址"
        }
    })
}
Promise.all(promiseAll).then((img) => {
    console.log(...img, '全部加载完成')
})
</script>
上一篇 下一篇

猜你喜欢

热点阅读