44
55const ATTR_DATA_SRC = 'data-src' ;
66const ATTR_DATA_LQIP = 'data-lqip' ;
7- const C_SHIMMER = 'shimmer' ;
8- const C_BLUR = 'blur' ;
7+
8+ const cover = {
9+ SHIMMER : 'shimmer' ,
10+ BLUR : 'blur'
11+ } ;
12+
13+ function removeCover ( clzss ) {
14+ $ ( this ) . parent ( ) . removeClass ( clzss ) ;
15+ }
916
1017function handleImage ( ) {
11- const $img = $ ( this ) ;
18+ if ( ! this . complete ) {
19+ return ;
20+ }
1221
13- if ( this . hasAttribute ( ATTR_DATA_LQIP ) && this . complete ) {
14- $img . parent ( ) . removeClass ( C_BLUR ) ;
22+ if ( this . hasAttribute ( ATTR_DATA_LQIP ) ) {
23+ removeCover . call ( this , cover . BLUR ) ;
1524 } else {
16- $img . parent ( ) . removeClass ( C_SHIMMER ) ;
25+ removeCover . call ( this , cover . SHIMMER ) ;
1726 }
1827}
1928
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- }
29+ /**
30+ * Switches the LQIP with the real image URL.
31+ */
32+ function switchLQIP ( ) {
33+ const $img = $ ( this ) ;
34+ const src = $img . attr ( ATTR_DATA_SRC ) ;
35+
36+ $img . attr ( 'src' , encodeURI ( src ) ) ;
37+ $img . removeAttr ( ATTR_DATA_SRC ) ;
2838}
2939
3040export function loadImg ( ) {
@@ -34,28 +44,18 @@ export function loadImg() {
3444 $images . on ( 'load' , handleImage ) ;
3545 }
3646
37- /* Images loaded from the browser cache do not trigger the 'load' event */
47+ // Images loaded from the browser cache do not trigger the 'load' event
3848 $ ( 'article img[loading="lazy"]' ) . each ( function ( ) {
3949 if ( this . complete ) {
40- $ ( this ) . parent ( ) . removeClass ( C_SHIMMER ) ;
50+ removeCover . call ( this , cover . SHIMMER ) ;
4151 }
4252 } ) ;
4353
54+ // LQIPs set by the data URI or WebP will not trigger the 'load' event,
55+ // so manually convert the URI to the URL of a high-resolution image.
4456 const $lqips = $ ( `article img[${ ATTR_DATA_LQIP } ="true"]` ) ;
4557
4658 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- }
59- } ) ;
59+ $lqips . each ( switchLQIP ) ;
6060 }
6161}
0 commit comments