Figure, Srcset and Lazy Loading

Lazy Loading

There is a new, although not particularly well supported attribute for <iframe> and <img/> tags: loading="lazy/eager/auto". This is huge because it allows the browser to determine when an image or iframe should be loaded as the user proceeds through a webpage instead of just loading them all at the start! No more JS to improve data use and performance - just a sweet native progressive enhancement.

A progressive enhancement, for those unaware, is one that only applies to browsers that have it implemented. It also means that older browsers that have not implemented it are not impacted because there is no change to the important parts of the markup. To add lazy loading to images or iframes simple do the following (note how the important parts are unchanged):

<img loading="lazy" alt="My Image" src="/path/to/my/image.png"/>

<iframe loading="lazy" width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Figure & Srcset

I like to use the <figure> element to display images inside my posts, and have recently (yesterday) converted to using the srcset attribute in <img/> elements to responsively serve differently sized images depending on the size of the screen. Note the use of loading="lazy" in the <img/> element:

        alt='This is my cool image!'
    <figcaption>(📷: Finn LeSueur) This is my cool image!</figcaption>

The second argument for each URL is the width of the image - this allows the browser to know the actual pixel width and do calculations in the background including screen width and pixel density to determine what size image is most appropriate. Very cool!

Good luck getting stuck into serving images that are appropriately sized for different screens and helping your users save both time and bandwidth!

– Finn 👋