Search code examples
imagelazy-loadingresponsive-imagespicturefill

Picturefill and lazyloading with lazysizes


I'm trying to get lazyloading with lazysizes and picturefill to work.

The lazyloading itself works if I just use a basic image:

<img class=lazyload data-srcset="http://placehold.it/301x301">

If I check the network tab in chrome, I can see that the image was loaded after the red line, so everything is fine:

enter image description here

Now I added a <picture> element with my responsive images and try to load that also lazy:

<picture>

    <!--[if IE 9]><video style="display: none;"><![endif]-->
    <source srcset="http://placehold.it/1370x301 1x, http://placehold.it/2055x450 2x" media="(min-width: 1024px)" />
    <source srcset="http://placehold.it/1023x300 1x, http://placehold.it/1534x450 2x" media="(min-width: 768px)" />
    <source srcset="http://placehold.it/767x300 1x, http://placehold.it/1151x450 2x" media="(min-width: 384px)" />
    <!--[if IE 9]></video><![endif]-->

    <img
            class="lazyload"
            style="width: 100%; max-width: 100%;"
            alt="Sample pic"
            data-srcset="http://placehold.it/383x300 1x, http://placehold.it/575x450 2x"
    />

</picture>

Unfortunately, this image is not lazyloaded but loaded directly: enter image description here

I also tried using only one src in the picture element image, but that doesn't make a difference.

According to the lazysizes doc, it should be possible to make this work together, so I guess I'm just missing a small detail?

Update: Lazysizes and Picturefill are both loaded in the <head>.


Solution

  • You need to use data-srcset instead of srcset:

    <picture>
    
        <!--[if IE 9]><video style="display: none;"><![endif]-->
        <source data-srcset="http://placehold.it/1370x301 1x, http://placehold.it/2055x450 2x" media="(min-width: 1024px)" />
        <source data-srcset="http://placehold.it/1023x300 1x, http://placehold.it/1534x450 2x" media="(min-width: 768px)" />
        <source data-srcset="http://placehold.it/767x300 1x, http://placehold.it/1151x450 2x" media="(min-width: 384px)" />
        <!--[if IE 9]></video><![endif]-->
    
        <img
                class="lazyload"
                style="width: 100%; max-width: 100%;"
                alt="Sample pic"
                data-srcset="http://placehold.it/383x300 1x, http://placehold.it/575x450 2x"
        />
    
    </picture>