2023-09-26 23:44:32 +03:00
|
|
|
/**
|
|
|
|
* Setting up image lazy loading and LQIP switching
|
|
|
|
*/
|
|
|
|
|
2023-09-29 00:07:03 +03:00
|
|
|
const ATTR_DATA_SRC = 'data-src';
|
|
|
|
const ATTR_DATA_LQIP = 'data-lqip';
|
2023-10-04 13:07:10 +03:00
|
|
|
|
|
|
|
const cover = {
|
|
|
|
SHIMMER: 'shimmer',
|
|
|
|
BLUR: 'blur'
|
|
|
|
};
|
|
|
|
|
|
|
|
function removeCover(clzss) {
|
2024-04-17 01:10:01 +03:00
|
|
|
this.parentElement.classList.remove(clzss);
|
2023-10-04 13:07:10 +03:00
|
|
|
}
|
2023-09-26 23:44:32 +03:00
|
|
|
|
2023-09-29 00:07:03 +03:00
|
|
|
function handleImage() {
|
2023-10-04 13:07:10 +03:00
|
|
|
if (!this.complete) {
|
|
|
|
return;
|
|
|
|
}
|
2023-09-26 23:44:32 +03:00
|
|
|
|
2023-10-04 13:07:10 +03:00
|
|
|
if (this.hasAttribute(ATTR_DATA_LQIP)) {
|
|
|
|
removeCover.call(this, cover.BLUR);
|
2023-09-29 00:07:03 +03:00
|
|
|
} else {
|
2023-10-04 13:07:10 +03:00
|
|
|
removeCover.call(this, cover.SHIMMER);
|
2023-09-29 00:07:03 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-04 13:07:10 +03:00
|
|
|
/**
|
|
|
|
* Switches the LQIP with the real image URL.
|
|
|
|
*/
|
|
|
|
function switchLQIP() {
|
2024-04-17 01:10:01 +03:00
|
|
|
const src = this.getAttribute(ATTR_DATA_SRC);
|
|
|
|
this.setAttribute('src', encodeURI(src));
|
|
|
|
this.removeAttribute(ATTR_DATA_SRC);
|
2023-09-29 00:07:03 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
export function loadImg() {
|
2024-04-17 01:10:01 +03:00
|
|
|
const images = document.querySelectorAll('article img');
|
2023-09-29 00:07:03 +03:00
|
|
|
|
2024-04-17 01:10:01 +03:00
|
|
|
if (images.length === 0) {
|
|
|
|
return;
|
2023-09-26 23:44:32 +03:00
|
|
|
}
|
|
|
|
|
2024-04-17 01:10:01 +03:00
|
|
|
images.forEach((img) => {
|
|
|
|
img.addEventListener('load', handleImage);
|
|
|
|
});
|
|
|
|
|
2023-10-04 13:07:10 +03:00
|
|
|
// Images loaded from the browser cache do not trigger the 'load' event
|
2024-04-17 01:10:01 +03:00
|
|
|
document.querySelectorAll('article img[loading="lazy"]').forEach((img) => {
|
|
|
|
if (img.complete) {
|
|
|
|
removeCover.call(img, cover.SHIMMER);
|
2023-09-29 00:07:03 +03:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-10-04 13:07:10 +03:00
|
|
|
// LQIPs set by the data URI or WebP will not trigger the 'load' event,
|
|
|
|
// so manually convert the URI to the URL of a high-resolution image.
|
2024-04-17 01:10:01 +03:00
|
|
|
const lqips = document.querySelectorAll(
|
|
|
|
`article img[${ATTR_DATA_LQIP}="true"]`
|
|
|
|
);
|
2023-09-29 00:07:03 +03:00
|
|
|
|
2024-04-17 01:10:01 +03:00
|
|
|
if (lqips.length) {
|
|
|
|
lqips.forEach((lqip) => {
|
|
|
|
switchLQIP.call(lqip);
|
|
|
|
});
|
2023-09-26 23:44:32 +03:00
|
|
|
}
|
|
|
|
}
|