-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazy-load.js
48 lines (43 loc) · 1.22 KB
/
lazy-load.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
!function(window){
/**
* Load Image (change it's source from data-original to src)
*
* @param {Node} el
*/
function loadImage (el) {
var src = el.getAttribute('data-original');
el.src = src;
el.className += ' loaded';
//also add class loaded to parent
el.parentNode.className += ' loaded';
}
/**
* Check's if given Image is in viewport
*
* @param {Node} el
* @returns {Boolean}
*/
function elementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0
&& rect.left >= 0
&& rect.top <= (window.innerHeight || document.documentElement.clientHeight)
)
}
/**
* Global method finding all images with data-original attribute that havent .loaded class
*
* @param {any} el
*/
window.processScroll = function() {
var q = document.querySelectorAll('img[data-original]:not(.loaded)');
for ( var i = 0; i<q.length; i++ ) {
if (elementInViewport(q[i])) {
loadImage(q[i]);
}
}
}
processScroll();
window.addEventListener('scroll',processScroll);
}(this);