前端开发那些事儿大前端

图片异步加载

2019-09-29  本文已影响0人  冷r
function creatImg(url) {
    return new Promise((resolve, reject) => {
        const oImg = new Image();
        oImg.onload = () => {
            resolve(oImg);
        };
        oImg.onerror = () => {
            reject(new Error(`img url:${url} is not find!`));
        };
        oImg.src = url;
    });
}

const imgList = ['/timg.jpg', '/xiaohai.jpg', '/timg.jpg', '/timg.jpg'];
const oImgList = [];

imgList.forEach(imgUrl => {
    oImgList.push(creatImg(imgUrl));
});

Promise.all(oImgList).then(oImg => {
    oImg.forEach(img => {
        document.body.append(img);
    });
});
上一篇 下一篇

猜你喜欢

热点阅读