简单有效的JavaScript图片预加载效果

2019-12-11    seo达人

首先编写一个简单的容器:



<style>

content {

    width: 600px;

    height: 100vh;

    overflow-y: auto;

}

 

content ul {

    width: 100%;

}

 

content ul li {

    width: 50%;

    float: left;

    margin: 20px 0;

    list-style: none;

}

 

content ul li p {

    width: 200px;

    height: 200px;

    overflow: hidden;

    margin: 0 auto;

    border: 1px solid #999999;

}

 

content ul li p img {

    width: 100%;

    display: block;

    position: relative;

    top: 50%;

    transform: translateY(-50%);

}

</style>

<div id="content">

   <ul>

   </ul>

</div>

然后,编写js代码:



let imageArr = [{

    img_url: "http://www.lexilisi.com/Uploadpth/c45cc952-dcb7-493c-a171-357d1b820b37.png",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_3.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_4.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_5.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_6.jpg",

}, {

    img_url: "http://xiaobanyou.com/static/images/xby_user_799.jpg",

}];

const lazyLoad = (src) => {

    //加载loading动画

    let _image = new Image();

    _image.src = './loading.gif';

    //加载需要展示的图片

    let image = new Image();

    image.src = src;

    //加载成功,将loading图片路径改成对应的真实路径

    image.onload = _ => image.src = .currentTarget.src;

    //加载失败,将loading图片路径改成默认图片路径

    image.onerror = _ => _image.src = './error.png';

    return _image;

}

let _content = document.getElementById('content');

let _ul = _content.getElementsByTagName('ul');

imageArr.forEach(value => {

    let _li = document.createElement('li');

    let _p = document.createElement('p');

    let _image = lazyLoad(value.img_url);

    _p.appendChild(_image);

    _li.appendChild(_p);

    _ul[0].appendChild(_li);

})

展示效果如图:







每个图片都是异步加载,加载完成后:







 






日历

链接

个人资料

蓝蓝设计的小编 http://www.lanlanwork.com

存档