Reputation: 1998
I've been deferring all of my images on my site (normal images or background image) with the following code
var imgDefer = document.querySelectorAll('img[data-deferred-image]');
for (var i=0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-deferred-image')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-deferred-image'));
}
}
var backgroundImgDefer = document.querySelectorAll('[data-deferred-bg-image]');
for (var i=0; i < backgroundImgDefer.length; i++) {
if(backgroundImgDefer[i].getAttribute('data-deferred-bg-image')) {
backgroundImgDefer[i].style.backgroundImage = 'url("' + backgroundImgDefer[i].getAttribute('data-deferred-bg-image') + '")';
}
}
This is currently being ran inside a window.onload
tag, which should work, but i've noticed that pagespeed ignores the fact they are being deferred, and just asks me to defer them.
I've noticed on the google defer images instructions it states
Lighthouse flags offscreen images that were requested before the Time To Interactive (TTI) event.
When should I call my defer code so that pagespeed/lighthouse audit actually pays attention to the fact i'm deferring it?
The code is definitely working, I can actively see it load the images after page load.
Upvotes: 1
Views: 813
Reputation: 692
As you know it's Offscreen Images to deal with this either use the premade small library like Lazy load offscreen images with lazysizes or use proper intersectionobserver
window.onlad will not help you to overcome Time To Interactive
Suggestion: You can even show a small thumbnail or image placeholder by default and once page is loaded you can replace them with high quality real images this way browser will not show the offscren images issues, for reference you can see how https://medium.com/ loads the images.
Upvotes: 1
Reputation: 3368
You may want to try to use requestIdleCallback and fallback to setTimeout
if not available.
You could alternatively not load them all and priorise those in view first.
Upvotes: 0