Usually, to implement lazy loading in HTML, instead of src
or srcset
attributes, we use data-src
or data-srcset
so that browser does not load images during speculative parsing. Later on, when Javascript is executed, and the user has scrolled near the image element, we load the actual image and update the src
or srcset
attribute’s value.
Two very popular lazy loading libraries lazysizes and vanilla-lazyload support responsive images out of the box.
Here are a few examples of using lazysizes.
Lazy loading responsive images in srcset and sizes
<img
sizes="(min-width: 1000px) 930px, 90vw"
data-srcset="small.jpg 500w,
medium.jpg 640w,
big.jpg 1024w"
data-src="medium.jpg"
class="lazyload" />
Using low quality placeholder in lazy loading
<img
src="low-quaity-placeholder.jpg"
sizes="(min-width: 1000px) 930px, 90vw"
data-srcset="small.jpg 500w,
medium.jpg 640w,
big.jpg 1024w"
data-src="medium.jpg"
class="lazyload" />
Lazy loading images in picture element
<picture>
<source
data-srcset="500.jpg"
media="(max-width: 500px)" />
<source
data-srcset="1024.jpg"
media="(max-width: 1024px)" />
<source
data-srcset="1200.jpg" />
<img src="fallback-image.jpg"
data-src="1024.jpg"
class="lazyload"
alt="image with artdirection" />
</picture>
You can learn more about responsive images from this guide - https://imagekit.io/responsive-images