-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (51 loc) · 1.63 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
export default class LazyLoader {
constructor(selector, rootMargin = '200px' ) {
this.selector = selector;
this.rootMargin = rootMargin;
this.observeTargets();
}
getTargetElements() {
return document.querySelectorAll(this.selector);
}
getIntersectionObserverOptions() {
return {
root: null,
rootMargin: this.rootMargin,
threshold: 0,
}
}
observeTargets() {
let targetElements = this.getTargetElements();
if (!targetElements || !targetElements.length) {
return;
}
targetElements = Array.from(targetElements);
if(!targetElements.filter(LazyLoader.isElementLazyLoadable).length) {
return; // No lazy loadable elements
}
// Create new IO with lazy load callback
const observer = new IntersectionObserver(this.handleIntersection, this.getIntersectionObserverOptions());
targetElements.forEach(el => {
observer.observe(el);
});
}
static isElementLazyLoadable(el) {
return !!(el.nodeName.toLowerCase() === 'img' && el.attributes['data-lazyload']);
}
// When a lazy load-able element intersects the IO's threshold and margin, load the image.
handleIntersection(entries, observer) {
entries.forEach(entry => {
/**
* When the IntersectionObserver is instantiated the callback is ran once
* as a detection for whether the element is in view or not.
*/
if (!entry.isIntersecting) {
return;
}
// Load the actual image by making setting src attribute equal to custom data-lazyload attribute.
entry.target.src = entry.target.attributes['data-lazyload'].value;
// Stop observing target, since it now has its image loaded.
observer.unobserve(entry.target);
});
}
};