Lazyloading is a good way to improve image performance, if you have a lot of images on the page that fall below the fold. By only loading images and other large assets when they're about to be displayed, you can greatly reduce the initial page weight and get the page on-screen for your users more quickly. For simple pages, or where SEO is important, you’ll probably want to leave loading up to the browser, but if your site is a good candidate or is already using this method, read on.
This post will cover how to use imgix with the major responsive design patterns and lazysizes, a popular responsive design library that provides fast lazyloading and lots of other features.You can get lazysizes and its installation instructions at Github.
Here's a basic imgix
srcset/sizes setup for two media queries. At a viewport of
640px or above, the image will display at 1/2 the viewport width. At less than 36em, it will display at the full viewport width. At those breakpoints, the browser will determine which image to load in from the
srcset based on the target size.
To add lazysizes to this setup, we need to add the
lazyload class to the image, and switch from
Similarly, you can add in lazysizes to an existing
<picture> element pattern. We'll start with the final example from our
<picture> element tutorial, which demonstrates art direction and device-pixel ratio support. Here's the original:
This photo has more granular breakpoints based on the desire to art-direct the cropping of the image for different page orientations and resolutions. The aspect ratio and cropping change to fit the width of the container, and the
dpr=2 versions of the image support high-DPR devices.
To add lazysizes support to this setup, we do the same as in the previous example. Just add the
lazyload class to the <img> element, and change the
src/srcset declarations to
Using imgix with lazysizes gives you a flexible framework for all responsive design patterns, ensuring that you images load quickly and at the correct size for their containers. lazysizes also enables you to lazyload other types of assets beyond images, such as scripts and iframes.