-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageElement.js
90 lines (70 loc) · 2.23 KB
/
ImageElement.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
88
89
90
class ImageElement extends HTMLElement{
constructor(){
super();
this.observer = false;
}
connectedCallback(){
this.style.display = 'flex';
this.style.justifyContent = 'center';
this.style.alignItems = 'center';
this.style.overflow = 'hidden';
if(this.dataset.src != null){
this.loadImage();
}
}
disconnectedCallback(){
this.lazyOff();
}
static get observedAttributes() {
return ['data-src', 'data-srcset', 'data-alt'];
}
attributeChangedCallback(name, oldValue, newValue){
if(name === 'data-src' || name === 'data-srcset'){
this.loadImage();
}else if(name === 'data-alt'){
if(this.img){
this.img.alt = this.dataset.alt;
}
}
}
loadImage(){
this.img = new Image();
this.img.dataset.src = this.dataset.src;
this.lazy();
this.img.style.width = '100%';
this.img.style.height = '100%';
this.img.style.objectFit = 'contain';
let loader = document.createElement('div');
loader.classList.add('loader');
loader.innerText = (typeof this.dataset.loader !== 'undefined') ? this.dataset.loader : 'Loading...';
this.innerHTML = loader.outerHTML;
this.img.onload = () => {
this.innerHTML = this.img.outerHTML;
};
}
lazy(){
/**
* @see https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video
*/
this.active = false;
this.lazyLoad();
}
lazyOff(){
this.observer = false;
}
lazyLoad(){
if (!this.active) {
this.active = true;
this.observer = new IntersectionObserver((entries) => {
if(entries[0].isIntersecting === true){
this.img.src = this.img.dataset.src;
if (typeof this.img.dataset.srcset != 'undefined') {
this.img.srcset = this.img.dataset.srcset;
}
}
});
this.observer.observe(this);
}
}
}
customElements.define('image-element', ImageElement);