2019-08-15 17:40:13 +00:00
|
|
|
/*
|
|
|
|
* Lazyloading images with Native API or IntersectionObserver
|
2021-04-21 00:27:38 +00:00
|
|
|
* TODO: Remove the features since it is depreciated by $wgNativeImageLazyLoading in 1.35
|
2019-08-15 17:40:13 +00:00
|
|
|
*/
|
2020-02-15 23:05:56 +00:00
|
|
|
|
2021-04-21 00:27:38 +00:00
|
|
|
/**
|
|
|
|
* @param {document} document
|
|
|
|
* @return {void}
|
|
|
|
*/
|
|
|
|
function main( document ) {
|
2020-08-12 16:37:43 +00:00
|
|
|
// Native API
|
|
|
|
if ( 'loading' in HTMLImageElement.prototype ) {
|
|
|
|
document.querySelectorAll( 'img.lazy' ).forEach( function ( img ) {
|
|
|
|
img.setAttribute( 'src', img.getAttribute( 'data-src' ) );
|
2020-08-20 16:36:50 +00:00
|
|
|
img.removeAttribute( 'data-src' );
|
2020-02-15 23:05:11 +00:00
|
|
|
|
2020-08-12 16:37:43 +00:00
|
|
|
if ( img.hasAttribute( 'data-srcset' ) ) {
|
|
|
|
img.setAttribute( 'srcset', img.getAttribute( 'data-srcset' ) );
|
2020-08-20 16:36:50 +00:00
|
|
|
img.removeAttribute( 'data-srcset' );
|
2020-02-15 23:05:56 +00:00
|
|
|
}
|
2020-02-15 23:05:11 +00:00
|
|
|
|
2020-08-12 16:37:43 +00:00
|
|
|
img.classList.remove( 'lazy' );
|
|
|
|
} );
|
|
|
|
} else {
|
|
|
|
// IntersectionObserver API
|
|
|
|
if ( typeof IntersectionObserver !== 'undefined' && 'forEach' in NodeList.prototype ) {
|
2021-04-21 00:27:38 +00:00
|
|
|
const observer = new IntersectionObserver( ( changes ) => {
|
2020-08-12 16:37:43 +00:00
|
|
|
if ( 'connection' in navigator && navigator.connection.saveData === true ) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-04-21 00:27:38 +00:00
|
|
|
changes.forEach( ( change ) => {
|
2020-08-12 16:37:43 +00:00
|
|
|
if ( change.isIntersecting ) {
|
|
|
|
change.target.setAttribute( 'src', change.target.getAttribute( 'data-src' ) );
|
2020-08-20 16:36:50 +00:00
|
|
|
change.target.removeAttribute( 'data-src' );
|
2020-02-15 23:05:11 +00:00
|
|
|
|
2020-08-12 16:37:43 +00:00
|
|
|
if ( change.target.hasAttribute( 'data-srcset' ) ) {
|
|
|
|
change.target.setAttribute( 'srcset', change.target.getAttribute( 'data-srcset' ) );
|
2020-08-20 16:36:50 +00:00
|
|
|
change.target.removeAttribute( 'data-srcset' );
|
2020-08-12 16:37:43 +00:00
|
|
|
}
|
2020-02-15 23:05:11 +00:00
|
|
|
|
2020-08-12 16:37:43 +00:00
|
|
|
change.target.classList.remove( 'lazy' );
|
|
|
|
observer.unobserve( change.target );
|
|
|
|
}
|
|
|
|
} );
|
2020-02-16 00:20:20 +00:00
|
|
|
} );
|
2020-08-12 16:37:43 +00:00
|
|
|
document.querySelectorAll( 'img.lazy' ).forEach( function ( img ) {
|
|
|
|
observer.observe( img );
|
|
|
|
} );
|
|
|
|
}
|
2020-02-15 23:05:56 +00:00
|
|
|
}
|
2020-02-16 00:20:20 +00:00
|
|
|
}
|
2020-08-12 16:37:43 +00:00
|
|
|
|
2021-04-21 00:27:38 +00:00
|
|
|
main( document );
|