Fork me on GitHub

lazyLoad图片懒加载

图片延迟加载lazyload,使用延迟加载在可提高网页下载速度。在大多数情况下,它也能帮助减轻服务器负载。

html:

1
<img class="datu lazy" src="./images/default.png" data-src="./images/img/1.jpg" alt="">

css:

1
2
3
4
.lazy {
width: 100%;
min-height: 100px;
}

custom.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var stuff = $('.lazy');
var quantity = stuff.length;
var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历
var placeholder = './images/default.png';
var clientHeight = window.innerHeight || document.documentElement.clientHeight; //可见区域高度
function lazyload() {
for (var i = n; i < quantity; i++) {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
if (stuff[i].offsetTop < clientHeight + scrollTop) {
if (stuff[i].getAttribute('src') == placeholder)

stuff[i].setAttribute('src', stuff[i].getAttribute('data-src'));
n++;
}
}
}
lazyload();
window.onscroll = lazyload;

lazyload.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var stuff = $('.lazy');
var quantity = stuff.length;
var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历
var placeholder = './images/default.png';
var clientHeight = window.innerHeight || document.documentElement.clientHeight; //可见区域高度
function lazyload() {
for (var i = n; i < quantity; i++) {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
if (stuff[i].offsetTop < clientHeight + scrollTop) {
if (stuff[i].getAttribute('src') == placeholder)

stuff[i].setAttribute('src', stuff[i].getAttribute('data-src'));
n++;
}
}
}
lazyload();
window.onscroll = lazyload;

支持作者