-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy-img.js
159 lines (132 loc) · 3.67 KB
/
lazy-img.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
export default class LazyImg {
static get OPTIONS() {
return {
maxWidth: 1920,
column: 80,
gutter: 28,
imgParams: ['c_fill', 'f_auto', 'q_auto'].join(),
bgParams: ['c_fill', 'f_auto', 'q_auto'].join(),
className: '.js-lazy-img',
handledClass: 'loaded',
accountId: 'idemo',
};
}
static get URL() {
return `https://res.cloudinary.com/${LazyImg.OPTIONS.accountId}/image/upload/`;
}
static get SUPPORTS_INTERSECTION_OBSERVER() {
return 'IntersectionObserver' in window;
}
constructor() {
this.options = LazyImg.OPTIONS;
this.getImages();
}
preloadImage(url) {
return new Promise((resolve, reject) => {
const image = new Image();
image.src = url;
image.onload = () => resolve(image);
image.onerror = () => reject(new Error('Could not load image at ' + url));
});
}
getImages() {
this.images = [...document.querySelectorAll('.js-lazy-load')];
if (!LazyImg.SUPPORTS_INTERSECTION_OBSERVER) {
this.loadAll(this.images);
return;
}
this.initObserver();
}
initObserver() {
if (this.observer) {
this.observer.disconnect();
}
const intersectionConfig = {
threshold: 0.01,
};
this.observer = new IntersectionObserver(
this.onIntersection,
intersectionConfig
);
this.observeImages();
}
observeImages() {
this.count = this.images.length;
this.images.forEach(image => {
if (image.classList.contains(this.options.handledClass)) {
return;
}
this.observer.observe(image);
});
}
onIntersection = entries => {
entries.forEach(entry => {
if (entry.intersectionRatio <= 0) {
return;
}
this.count--;
this.observer.unobserve(entry.target);
this.loadImage(entry.target);
});
if (this.count === 0) {
this.observer.disconnect();
}
};
snapToGrid(renderWidth) {
const colCalc = n =>
n * (this.options.column + this.options.gutter) - this.options.gutter;
let ncols = 1;
let snapWidth = 0;
while (snapWidth < this.options.maxWidth) {
snapWidth = colCalc(ncols);
if (renderWidth - snapWidth <= 0) {
return colCalc(ncols);
}
ncols++;
}
return this.options.maxWidth;
}
loadAll(images) {
images.forEach(image => this.loadImage(image));
}
loadImage(image) {
if (image.classList.contains(this.options.handledClass)) {
return;
}
const id = image.dataset.src;
if (!id) {
return;
}
const { width, height } = image.getBoundingClientRect();
if (image.tagName === 'IMG') {
this.applyImg(image, id, width);
} else {
this.applyBg(image, id, width, height);
}
}
applyImg(image, id, width) {
const imageParams = [
'w_' + this.snapToGrid(width),
LazyImg.IMG_PARAMS,
image.dataset.ratio && 'ar_' + image.dataset.ratio,
].join(',');
const url = `${LazyImg.URL}/${imageParams}/${id}`;
this.preloadImage(url)
.then(_ => {
image.removeAttribute('srcset');
image.setAttribute('src', url);
image.classList.add(this.options.handledClass);
})
.catch(_ => console.error(`Image ${url} is broken`));
}
applyBg(image, id, width, height) {
const imageParams = `w_${this.snapToGrid(width)},h_${height > 1000 ? 1000 : 100 * Math.round(height / 100)},${LazyImg.BG_PARAMS}`;
const url = `${LazyImg.URL}/${imageParams}/${id}`;
this.preloadImage(url)
.then(_ => {
image.style.backgroundImage = `url(${url})`;
image.classList.add(this.options.handledClass);
})
.catch(_ => console.error(`Image ${url} is broken`));
}
}