Lightweight lazy loading with Netlify Large Media

An example of powering picture elements for responsive images with lazy loading, using Netlify Large Media.

Take a look at the code on GitHub, or read on, for more explanation and examples.

A snazzy lighthouse

Image transformation

By managing our source image asset files with Netlify Large Media, we can take advantage of the ability to perform on-the-fly image transformations to deliver resized and cropped versions of the images directly from Netlify's ADN.

Netlify transforms and caches image assets if we add querystring parameters to our image src URLs.

For example, the image below can be served in any size:

Abstract with helper URLs

To clean these URLs up a little, we can use Netlify's Redirects API to create some more friendly and abstracted URLs which proxy to the querystring decorated URLs:

The redirects config uses fully qualified URLs here, so that we can see the same transformations while developing locally with Netlify Dev

Using the picture element

These images have been added to the page in various sizes, using the picture element with multiple image sources.

A snazzy lighthouseA snazzy lighthouseA snazzy lighthouseA snazzy lighthouse

A picture helper

Whatever tool you use to generate your HTML, chances are that it includes a facility to make shortcodes or macros.

This example uses a static site generator called 11ty which gives us the ability to make a shortcode to output picture tags with many image source attributes including transformation parameters automatically added to the image urls.

This shortcode:

{% lazypicture lighthouse.jpg "A snazzy lighthouse" %}

outputs this html:

<picture class="lazy lazy-initial">
<source srcset="/images/tiny/lighthouse.jpg" media="(min-width: 1200px)">
<source srcset="/images/tiny/lighthouse.jpg" media="(min-width: 740px)">
<img src="/images/tiny/lighthouse.jpg" alt="A snazzy lighthouse" />
</picture>

This sets each image source to use a tiny (typically less that 1k) version of the image. With some CSS, we size the image to fit and add some blurring to smooth it all down nicely.

Then, thanks to the magic of the browser's Intersection Observer API. We can detect when our images come into the viewport, and use JavaScript to update our image sources to use more appropriately sized simages in our responsive picture element.

Removing the CSS class which applies the blur once our new image source is loaded completes the effect.

Get started with Netlify Large Media

Need some reference code to get you going? You can clone the code for this site to use as an example.

Once cloned, you can find examples and documentation on how to configure Netlify Large Media, in the docs.