-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy-load.js
45 lines (43 loc) · 1.37 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
'use strict';
let lazy = {
timeout: null,
/**
* Initialize listeners
*/
init: function() {
this.load();
window.addEventListener('scroll', this.load.bind(this));
window.addEventListener('resize', this.load.bind(this));
window.addEventListener('orientationChange', this.load.bind(this));
},
/**
* Defer loading until a bit after event stop firing, prevents call spamming
*/
load: function() {
if (this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(this.loadImages.bind(this), 50);
},
/**
* Load images that are not yet loaded and are at least partially visible
*/
loadImages: function() {
let visibleTop = window.pageYOffset;
let visibleBottom = visibleTop + window.innerHeight;
document.querySelectorAll('.lazy').forEach(image => {
let imageTop = image.offsetTop;
let imageBottom = imageTop + image.offsetHeight;
if (imageTop < visibleBottom && imageBottom > visibleTop) {
let src = ''
if (image.classList.contains('full')) src =
image.getAttribute('src').replace('_lazy', '');
else src = image.getAttribute('src').replace('_lazy', '_preview');
image.setAttribute('src', src);
image.classList.remove('lazy');
}
});
}
};
if (document.readyState == 'Loading')
window.addEventListener('DOMContentLoaded', lazy.init);
else
lazy.init();