I imagine that slowly walking in Louvre surrounded by timeless art could be very soothing. Though the gallery I have in mind for today's project can be just as enjoyable.
I'm talking about photo galleries that you can find on e-commerce sites, portfolios, blogs, landing pages and even social networks. Depending on the use case a photo gallery have animated transitions, thumbnails, zoom and bunch of other features, but more often than not images are loaded lazily - only when they are needed that is.
And that is what I suggest we tackle today: a gallery with lazily loaded images.
Lazy Images: requirements and recipe
As a user I'd like images on the page to be loaded only when they are visible or about to be visible, so that I can load pages faster and spare some traffic.
Here's an example from NightCafe with AI generated images prompted by yours truly:
Using Chrome's built-in network throttling functionality we can observe how images are loaded:
Implementations, look and feel can vary and, as usual, entirely up to you, as long as requirements are met:
Requirements
- Images that are always visible on initial page load should be loaded normally
- Other images are loaded only when they are entering viewport
- All images should have descriptive alt text
- Gallery should be keyboard accessible
- Images sources should match the size of the image tile
Recipe
- Start with one static image markup for mobile sized display
- Using first image as a template add a couple more images
- Ensure that sizes & alt text descriptions match requirements for each image
- Implement gallery layout
- Add lazy loading functionality
- Adjust layout for bigger devices
- Ensure that gallery is accessible
- Give yourself a round of well deserved praise!
Hints
There's a built loading="lazy"
attribute that would do the trick efficiently but quite crude: you can start with it and see if you'd like to do some custom lazy loader instead.
One could use srcset
to provide a set of images of varying sizes to allow the browser to choose most suitable one for current resolution.
Make sure to set image sizes or ratios explicitly to avoid layout shifts when images do load.
Hard Mode: Image Specific Placeholders
While lazy loading would work with or without placeholders, it would be so much nicer to give a user a hint into how the image would look like once it's loaded. Or even better: slowly fade into it.
Take BlurHash for example:
In this case blurhash is a tiny string that can be rendered into an image fairly quick without loading any additional data.
Though one needs a canvas to render them, can there be a better way to inline a small image?
Share your creations and feedback and see you tomorrow!
Liked the idea a lot and would love to have it all year long?
Top comments (0)