Skip to content

Commit 62b1f9a

Browse files
committed
Create img-loading.js
1 parent 96408ac commit 62b1f9a

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Setting up image lazy loading and LQIP switching
3+
*/
4+
5+
const ATTR_DATA_SRC = 'data-src';
6+
const ATTR_DATA_LQIP = 'data-lqip';
7+
8+
const cover = {
9+
SHIMMER: 'shimmer',
10+
BLUR: 'blur'
11+
};
12+
13+
function removeCover(clzss) {
14+
this.parentElement.classList.remove(clzss);
15+
}
16+
17+
function handleImage() {
18+
if (!this.complete) {
19+
return;
20+
}
21+
22+
if (this.hasAttribute(ATTR_DATA_LQIP)) {
23+
removeCover.call(this, cover.BLUR);
24+
} else {
25+
removeCover.call(this, cover.SHIMMER);
26+
}
27+
}
28+
29+
/**
30+
* Switches the LQIP with the real image URL.
31+
*/
32+
function switchLQIP() {
33+
const src = this.getAttribute(ATTR_DATA_SRC);
34+
this.setAttribute('src', encodeURI(src));
35+
this.removeAttribute(ATTR_DATA_SRC);
36+
}
37+
38+
export function loadImg() {
39+
const images = document.querySelectorAll('article img');
40+
41+
if (images.length === 0) {
42+
return;
43+
}
44+
45+
images.forEach((img) => {
46+
img.addEventListener('load', handleImage);
47+
});
48+
49+
// Images loaded from the browser cache do not trigger the 'load' event
50+
document.querySelectorAll('article img[loading="lazy"]').forEach((img) => {
51+
if (img.complete) {
52+
removeCover.call(img, cover.SHIMMER);
53+
}
54+
});
55+
56+
// LQIPs set by the data URI or WebP will not trigger the 'load' event,
57+
// so manually convert the URI to the URL of a high-resolution image.
58+
const lqips = document.querySelectorAll(
59+
`article img[${ATTR_DATA_LQIP}="true"]`
60+
);
61+
62+
if (lqips.length) {
63+
lqips.forEach((lqip) => {
64+
switchLQIP.call(lqip);
65+
});
66+
}
67+
}

0 commit comments

Comments
 (0)