Lazy loading images on a website
2018-05-22I guess that you as much as everybody else wants your website to be as fast as possible for your users. When you are done with making as fast as you can, you can take the next step and that is to make it appear as if it's even faster. One way to do that is to lazy load the images on your site. This means that you wait with loading the images until everything else is loaded. The images will be loaded asynchronously in the background. The good thing about this way is that your users will be able to start using the site before all images have been loaded.
There are several ways to achieve this behavior and there are libraries that you can use to achieve it also, but here we are going to look at a simple solution that you easily can achieve yourself on your website.
Ok, let's do it then!
The first step you need to do is to replace the src tag with data-lazy-src in the image tag, like this.
<img data-lazy-src="example.jpg" alt="this image shows an example" />
To make this look a bit nice also, we add a some css. First, we have some css that hides the image before it has been loaded and then let the image fade-in when it has been fully loaded.
<style>
img {
opacity: 1;
transition: 0.4 sec;
}
Img[data-src] {
opacity: 0;
}
</style>
If you do this change first and load your page, you will then notice that the image is not loaded. So, we need to add this JavaScript to load the images also.
<script>
[].forEach.call(document.querySelectorAll("img[data-lazy-src]"),
function (img) {
img.setAttribute("src", img.getAttribute("data-lazy-src"));
img.onload = function () {
img.removeAttribute("data-lazy-src");
};
});
</script>
Nice that it is all you have to do, to get your images lazy loaded and your site will appear faster than before.
There is one more thing that you can do to make it more robust, since we now use JavaScript to load the image our users that do not have JavasScript enable in their browser will not see any images at all. But we can fix that with the tag <NOSCRIPT>
Just add these lines below the img tag, to support browsers without JavaScript.
<noscript>
<img data-lazy-src="example.jpg" alt="this image shows an example">
</noscript>
To be able to see if it works, you can go into the developer tools in the Chrome browser and then select the 3 dots to come to the settings page. On the settings page you check the Disable JavaScript checkbox to see that it actually works.
That was lazy loading of images for a website.