Member-only story
Lazy Loading Images
Lazy loading images is the practice of deferring their loading until the user actually needs them, generally when the user scrolls towards them in the viewport. ‘Lazy loading’ can also be applied to other types of assets like CSS and JS, but that means something slightly different, and so is a topic for another time 😏.
You can implement image lazy loading on your website in two ways:
- A generic browser-API-based approach
- With custom Javascript, using the Intersection Observer API
If you want a fast effective solution that is supported in all major browsers minus safari, the browser-based approach might be right for you. If you need tighter control over the loading behavior of the images you might want to use Javascript. One customization might be to bring in custom thumbnails for each of the site images before it’s loaded, or insert a custom animation as the image comes into focus. Let’s take a look at each approach.
Browser Based Approach
This approach to lazy loading images is as simple as adding an additional attribute to your HTML element. When you define an image, do it like so:
<img src="image.jpg" alt="..." loading="lazy">