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) {
|
|
|
|
$(this).parent().removeClass(clzss);
|
|
|
|
}
|
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() {
|
|
|
|
const $img = $(this);
|
|
|
|
const src = $img.attr(ATTR_DATA_SRC);
|
|
|
|
|
|
|
|
$img.attr('src', encodeURI(src));
|
|
|
|
$img.removeAttr(ATTR_DATA_SRC);
|
2023-09-29 00:07:03 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
export function loadImg() {
|
|
|
|
const $images = $('article img');
|
|
|
|
|
|
|
|
if ($images.length) {
|
|
|
|
$images.on('load', handleImage);
|
2023-09-26 23:44:32 +03:00
|
|
|
}
|
|
|
|
|
2023-10-04 13:07:10 +03:00
|
|
|
// Images loaded from the browser cache do not trigger the 'load' event
|
2023-09-29 00:07:03 +03:00
|
|
|
$('article img[loading="lazy"]').each(function () {
|
|
|
|
if (this.complete) {
|
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
|
|
|
// 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.
|
2023-09-29 00:07:03 +03:00
|
|
|
const $lqips = $(`article img[${ATTR_DATA_LQIP}="true"]`);
|
|
|
|
|
|
|
|
if ($lqips.length) {
|
2023-10-04 13:07:10 +03:00
|
|
|
$lqips.each(switchLQIP);
|
2023-09-26 23:44:32 +03:00
|
|
|
}
|
|
|
|
}
|