-
Notifications
You must be signed in to change notification settings - Fork 9
/
simple-lazyload.js
50 lines (44 loc) · 1.41 KB
/
simple-lazyload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
(function (window) {
var images = Array.prototype.slice.call(document.querySelectorAll('img[data-original]'));
function elementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.bottom >= 0
&& rect.left >= 0
&& rect.top <= (window.innerHeight || document.documentElement.clientHeight)
);
}
function loadImage(el, fn) {
var img = new Image()
, src = el.getAttribute('data-original');
img.onload = function () {
el.src = src;
fn ? fn() : null;
};
img.src = src;
}
function processImages() {
for (var i = 0; i < images.length; i++) {
if (elementInViewport(images[i])) {
(function(index){
var loadingImage = images[index];
loadImage(loadingImage, function () {
images = images.filter(function(t) {
return loadingImage !== t;
});
});
})(i);
}
};
}
function throttle(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function () {
method.call(context);
}, 500);
}
processImages();
window.addEventListener('scroll', function () {
throttle(processImages, window);
});
})(this);