问题描述
我的一个网站的LCP确实很差,为4.6。我意识到,在没有主动延迟加载我的图像的情况下,LCP是2.0。通过使用lazyload也增加了TCB。因此,我认为这一定是我的不良JS技能,因此可以给我一个提示吗?
我的实际代码:
let lazyImages = [...document.querySelectorAll('img[data-src],iframe[data-src],div[data-bg],header[data-bg]')];
let inAdvance = 300;
function lazyLoad() {
lazyImages.forEach(image => {
if ( !image.classList.contains( 'lazyloaded' ) && !image.classList.contains( 'none' ) && image.getBoundingClientRect().top <= window.innerHeight + inAdvance && image.getBoundingClientRect().bottom >= 0) {
if( image.hasAttribute( 'data-src' ) ){
image.src = image.dataset.src;
}
if( image.hasAttribute( 'data-bg' ) ){
image.setAttribute( 'style','background-image:url( ' + image.dataset.bg + ' );' );
}
image.classList.add('lazyloaded');
//image.onload = () => image.classList.add('lazyloaded');
}
})
}
window.addEventListener( 'scroll',lazyLoad,{passive: true} );
window.addEventListener( 'resize',{passive: true} );
window.addEventListener( 'slick',{passive: true} );
我已经尝试用观察者替代,但是tcb或lcp并没有任何改善。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)