Images that lazy load are nothing new. The reasons behind doing so are varied, but if you are someone who cares about site speed, lazy loading recently became a lot more important.
If you use PageSpeed Insights at all to check on the speed of your website, then you probably noticed that Google recently made some significant changes. They now use Lighthouse as the basis for their speed results.
What does that mean exactly? Well, the short version is twofold. Firstly, the results are far more comprehensive. Much more is taken into account and weighted differently than it has been in the past. Secondly, this means that it takes a lot more work to get a good speed score, and that perhaps what is considered a “good score” has changed.
Luckily, there seems to be a recurring theme: images. The way images are handled and optimized are weighted heavily under the new algorithms. You may notice three recommendations related to images:
- Serve images in next-gen formats
- Properly size images
- Defer offscreen images
All three of these recommendations are aimed at reducing the amount of data that needs to be loaded before a website can be viewed. Luckily, lazy loading your images (and optimizing them prior to uploading them) can satisfy these requirements and can boost your speed score considerably.
In the near future, I will be writing another post about how to handle the other recommendations from Google, but let’s go ahead and get to lazy loading.
Setting Up the Scripts
First thing we will want to do is grab the scripts we will need. We will be using Lazyload by Verlok. Let’s include the following script:
<script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@12.0.0/dist/lazyload.min.js"></script>
We also need to include a quick initialization function. In this, we will include the class name on which this function will run. Here’s the function we need to include:
var lazyLoadInstance = new LazyLoad({
elements_selector: ".lazy"
});
With this function in place, any image that we assign the class lazy will be lazy loaded. You can, of course, change this class to anything you’d like, just be certain to change the reference to it.
Adding an Image
We are going to change the markup of our images slightly. Instead of the normal src attribute, we will use data-src instead. Something like this:
<img class="lazy" data-src="/path/to/my/image.jpg" />
And that’s it! This image will now lazy loaded. Now, we just need to run our images through an image optimizer before uploading them (and use the actual image at the actual size we need). If we implement the same thing on all of our images, the three recommendations above are satisfied!
What About Background Images?
Glad you asked! If you want to lazy load a background image, you can use the markup below to do that:
<div class="lazy" data-bg="url(/path/to/my/image.jpg)"></div>
Easy. Deceptively simple. But, it works.
You are a genius AND you write so clearly! thank you.