Lazy loading images means loading images on websites asynchronously — that is, after the above-the-fold content is fully loaded, or even conditionally, only when they appear in the browser’s viewport. This means that if users don’t scroll all the way down, images placed at the bottom of the page won’t even be loaded.
– Sitepoint
The Situation
Think you have an image called my-image.png
that takes 5 seconds to load, and you throw in an img
tag to your site like:
<img src="my-image.png">
That will add 5 seconds, more or less to your site’s load time. You don’t want that to happen, do you? But you can’t just go on and delete your image from your site and pretend that nothing had happened. Then how can I make my site faster but keep the images?? The solution to this problem is called Lazy Loading!
Lazy loading (also known as asynchronous loading) is a design commonly used in computer programming and mostly in web design and development to defer initialization of an object until the point at which it is needed
– Wikipedia
Solution
So how can I lazy load my images??
To lazy load your sites images, you need to use a little JavaScript
. Don’t worry!! It’s easier than you think, thanks to an amazing library called Lozad.js
.
To use this library, you just have to put the following at the end of your html
file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js"></script>
<script>lozad().observe();</script>
And add the class lozad
to your img
elements, then change the src
attribute to data-src
:
<img class="lozad" data-src="my-image.png">
Finally, see the magic work!
You will see that the image will start loading after you scroll down to it. This will improve your site’s initial load time.
Live Example: Go to my site, and scroll down to the Latest News section. You will see that the thumbnails load after you scroll down to them. (and if you want source code of that site - https://github.com/Dev-I-J/JNote-Site)
PS: Sorry for the bad grammar (or whatever).