|
2 | 2 | * Setting up image lazy loading and LQIP switching |
3 | 3 | */ |
4 | 4 |
|
5 | | -export function loadImg() { |
6 | | - const $images = $('main img[loading="lazy"]'); |
7 | | - const $lqip = $('main img[data-lqip="true"]'); |
| 5 | +const ATTR_DATA_SRC = 'data-src'; |
| 6 | +const ATTR_DATA_LQIP = 'data-lqip'; |
| 7 | +const C_SHIMMER = 'shimmer'; |
| 8 | +const C_BLUR = 'blur'; |
8 | 9 |
|
9 | | - if ($images.length > 0) { |
10 | | - $images.on('load', function () { |
11 | | - /* Stop shimmer when image loaded */ |
12 | | - $(this).parent().removeClass('shimmer'); |
13 | | - }); |
| 10 | +function handleImage() { |
| 11 | + const $img = $(this); |
14 | 12 |
|
15 | | - $images.each(function () { |
16 | | - /* Images loaded from the browser cache do not trigger the 'load' event */ |
17 | | - if ($(this).prop('complete')) { |
18 | | - $(this).parent().removeClass('shimmer'); |
19 | | - } |
20 | | - }); |
| 13 | + if (this.hasAttribute(ATTR_DATA_LQIP) && this.complete) { |
| 14 | + $img.parent().removeClass(C_BLUR); |
| 15 | + } else { |
| 16 | + $img.parent().removeClass(C_SHIMMER); |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +/* Switch LQIP with real image url */ |
| 21 | +function switchLQIP(img) { |
| 22 | + // Sometimes loaded from cache without 'data-src' |
| 23 | + if (img.hasAttribute(ATTR_DATA_SRC)) { |
| 24 | + const $img = $(img); |
| 25 | + const dataSrc = $img.attr(ATTR_DATA_SRC); |
| 26 | + $img.attr('src', encodeURI(dataSrc)); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +export function loadImg() { |
| 31 | + const $images = $('article img'); |
| 32 | + |
| 33 | + if ($images.length) { |
| 34 | + $images.on('load', handleImage); |
21 | 35 | } |
22 | 36 |
|
23 | | - if ($lqip.length > 0) { |
24 | | - $lqip.each(function () { |
25 | | - /* Switch LQIP with real image url */ |
26 | | - const dataSrc = $(this).attr('data-src'); |
27 | | - $(this).attr('src', encodeURI(dataSrc)); |
28 | | - $(this).removeAttr('data-src data-lqip'); |
| 37 | + /* Images loaded from the browser cache do not trigger the 'load' event */ |
| 38 | + $('article img[loading="lazy"]').each(function () { |
| 39 | + if (this.complete) { |
| 40 | + $(this).parent().removeClass(C_SHIMMER); |
| 41 | + } |
| 42 | + }); |
| 43 | + |
| 44 | + const $lqips = $(`article img[${ATTR_DATA_LQIP}="true"]`); |
| 45 | + |
| 46 | + if ($lqips.length) { |
| 47 | + const isHome = $('#post-list').length > 0; |
| 48 | + |
| 49 | + $lqips.each(function () { |
| 50 | + if (isHome) { |
| 51 | + // JavaScript runs so fast that LQIPs in home page will never be detected |
| 52 | + // Delay 50ms to ensure LQIPs visibility |
| 53 | + setTimeout(() => { |
| 54 | + switchLQIP(this); |
| 55 | + }, 50); |
| 56 | + } else { |
| 57 | + switchLQIP(this); |
| 58 | + } |
29 | 59 | }); |
30 | 60 | } |
31 | 61 | } |
0 commit comments