Search code examples
htmllighthouse

Lighthouse keeps showing Defer offscreen images


So every time I run lighthouse evaluation, it keeps telling me to "Defer offscreen images", now, what they recommend is to use their script and to set the images like this :

<img data-src="images/flower3.png" class="lazyload" alt="">

And this is what I have:

    <picture>
      <source sizes="(min-width:1025px) 25vw,(min-width:0px) 100vw" 
       srcset="https://thumbor.mypage/YiZprbZxOEdzieJbcj8ZnIKIrE4=/640x0/https%3A%2F%2Fmyimage.jpg 640w,...">
      <img alt="" sizes="(min-width:1025px) 25vw,(min-width:0px) 100vw" 
         data-object-fit="cover" 
         class=" ls-is-cached lazyloaded" 
         data-src="https://thumbor.mypage/yoi8S4dSPBIU5ekNg6x7NvFFFPM=/320x0/https%3A%2F%2Fmyimage.jpg" 
         srcset="https://thumbor.mypage/YiZprbZxOEdzieJbcj8ZnIKIrE4=/640x0/https%3A%2F%2Fmyimage.jpg 640w,https://thumbor.mypage/qoSnHcwy_fuA8C2gJaKnxnCJ00A=/1024x0/https%3A%2F%2Fmyimage.jpg 1024w,...">
    </picture>

So as you can see, I check the two things they ask for to match the right code: the lazyload class and the data-src attribute, maybe I'm missing something but for some reason, it only fails with a couple images. please help!


Solution

  • Short Answer

    The second an image has a src or srcset attribute set it will load the image. You need to use a lazy load library that supports the <picture> element and make sure you haven't set the src or srcset on your <picture> elements.

    Long Answer

    You have misunderstood a key aspect here. The class="lazyload" and data-src="images/flower3.png" are part of a lazy load solution using JavaScript. You can't just copy these attributes without the related JavaScript code.

    With their example (which I assume is this example of lazy loading as you did not link it in your question) there is a script you must include in order to make lazy loading work.

    If you look at their example these <img> elements do not have a src attribute set and so they are invalid and will not load the image.

    What the script does is look for <img> elements that have a class of lazyload and then look for the data-src attribute.

    It then takes whatever is in the data-src attribute and adds that to the src attribute of the image once the image is within the viewport.

    This then makes the image valid (as an <img> element must have a src attribute to be valid and actually load the image) and so it loads.

    In your example you already have the src set via the srcset attribute in your HTML so the images are loaded instantly, the data-src does nothing in this case.

    I am not sure whether the lazy loading library in that example works with <picture> elements (it appears to want you to use an <img> element with data attributes for media queries) so you may want to research a lazy loading library that works with the <picture> element now that you (hopefully) understand why your implementation is not working.