forked from 1000ch/lazyload-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazyload-image.js
87 lines (69 loc) · 1.72 KB
/
lazyload-image.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
export default class LazyloadImage extends HTMLImageElement {
static get FALLBACK_IMAGE() {
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR42gEFAPr/AP///wAI/AL+Sr4t6gAAAABJRU5ErkJggg==';
}
static get observedAttributes() {
return [
'offset'
];
}
constructor(width, height) {
super(width, height);
this.originalSrc = this.currentSrc || this.src;
this.originalSrcset = this.srcset;
this.src = LazyloadImage.FALLBACK_IMAGE;
this.srcset = "";
this.onIntersect = this.onIntersect.bind(this);
}
connectedCallback() {
this.observe();
}
disconnectedCallback() {
this.unobserve();
}
get offset() {
return this.getAttribute('offset');
}
set offset(value) {
this.setAttribute('offset', value);
}
get observer() {
if (!this.intersectionObserver) {
this.intersectionObserver = new IntersectionObserver(this.onIntersect, {
rootMargin: this.offset
});
}
return this.intersectionObserver;
}
observe() {
this.observer.observe(this);
}
unobserve() {
this.observer.unobserve(this);
this.observer.disconnect();
}
onIntersect(entries) {
if (entries.length === 0) {
return;
}
if (entries[0].intersectionRatio <= 0) {
return;
}
this.addEventListener('load', () => {
this.unobserve();
});
this.addEventListener('error', () => {
this.src = LazyloadImage.FALLBACK_IMAGE;
this.unobserve();
});
this.src = this.originalSrc;
this.srcset = this.originalSrcset;
}
attributeChangedCallback(name, oldValue, newValue) {
if (this.observer === null) {
return;
}
this.unobserve();
this.observe();
}
}