延迟加载是一种优化技术,它会延迟内容的下载和渲染,直到它们在屏幕上可见,延迟加载本质上是延迟图像的加载,直到用户向下滚动页面(图像进入访客视线),延迟加载是提高 WordPress 页面速度的好方法。延迟加载是一种在我们滚动过去之前防止图像加载的方法。所幸的是自从Wordpress 5.5以后,其内置了延迟加载功能。但它没有感官上的体验。本文教程是增强了内置的延迟加载功能,在感官上给用户动画延迟加载图像。下面是代码分享。
步骤 1:替换 src属性
注意:WordPress 5.5及以后的版本默认通过向所有图像添加loading="lazy"
属性引入了原生延迟加载。因此,您不再需要创建自己的。
在WordPress中,我们可以通过filter并用正则表达式替换src
或 srcset
:
add_filter( 'the_content', 'my_lazyload_content_images' );
add_filter( 'widget_text', 'my_lazyload_content_images' );
add_filter( 'wp_get_attachment_image_attributes', 'my_lazyload_attachments', 10, 2 );
// Replace the image attributes in Post/Page Content
function my_lazyload_content_images( $content ) {
$content = preg_replace( '/(<img.+)(src)/Ui', '$1data-$2', $content );
$content = preg_replace( '/(<img.+)(srcset)/Ui', '$1data-$2', $content );
return $content;
}
// Replace the image attributes in Post Listing, Related Posts, etc.
function my_lazyload_attachments( $atts, $attachment ) {
$atts['data-src'] = $atts['src'];
unset( $atts['src'] );
if( isset( $atts['srcset'] ) ) {
$atts['data-srcset'] = $atts['srcset'];
unset( $atts['srcset'] );
}
return $atts;
}
步骤 2:添加滚动侦听器
当图像到达您的视口时,它应该将data-src
替换为 src
,这样图像将开始加载。
( function() { 'use strict';
let images = document.querySelectorAll('img[data-src]');
document.addEventListener('DOMContentLoaded', onReady);
function onReady() {
// Show above-the-fold images first
showImagesOnView();
// scroll listener
window.addEventListener( 'scroll', showImagesOnView, false );
}
// Show the image if reached on viewport
function showImagesOnView( e ) {
for( let i of images ) {
if( i.getAttribute('src') ) { continue; } // SKIP if already displayed
// Compare the position of image and scroll
let bounding = i.getBoundingClientRect();
let isOnView = bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth);
if( isOnView ) {
i.setAttribute( 'src', i.dataset.src );
if( i.getAttribute('data-srcset') ) {
i.setAttribute( 'srcset', i.dataset.srcset );
}
}
}
}
})();
步骤3:添加css动画
img[data-src] {
opacity: 0;
transition: opacity .25s ease-in-out;
will-change: opacity;
}
img[data-src][src] {
opacity: 1;
}