One of my websites has a really bad LCP, 4.6. I realized that without active lazyload my images, the LCP is 2.0 . The TCB increased by using lazyload, too. So Im thinking it must be my bad JS-Skills, so could give me anyone of you a hint?
My actual code:
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', lazyLoad, {passive: true} );
window.addEventListener( 'slick', lazyLoad, {passive: true} );
I've already tried a replacement with observer, but there wasnt any improvement by tcb or lcp.
lazyLoad();
My HTML-Markup look like this:<img data-src="path to file" src="path to placeholder"/>
– Flanna