Lazy Load Images: How to Optimize Images to Improve Website Performance
Images are very essential part of a webpage. Modern websites or softwares are impossible to imagine without them. But unfortunately they are one of the reasons for performance reduction in the webpages. A single image can contain the size of the whole page by itself, so the webpage takes long time to load with just 2-3 heavy images or contents. This has a significant bad effect on the performance which can cause you to lose traffic or get lower in search engine ranks. Google prefers the websites which take no more than 3 seconds to load. So what to do on this? Should we skip using images we love? Do the best websites have any better approach to handle this issue? Yes, one of the solution is lazy loading to the images. Lets see how we can do that in this tutorial.
Images can hurt your web performance
Images are one of the heaviest resources in a webpage, higher the resolution of the image, higher the bandwidth will be required to load the page. Traditionally, all the images load simultaneously, irrespective of whether they are visible to user properly or not. This type of procedure wastes a lot of bandwidth, hurts performance and occurs delay to display the proper content to the user, which is in a word frustrating. This can result in users or customers denies to continue with your website, lose a potential buyer or demolishing your brand value. So you can get an idea, how important it is to properly manage your images to generate the best output for your website.
Impact of Images on Search Engine Rankings
Google's core web vitals always emphasize on the best performance aka site speed and user experience. Websites which takes more than 3s to load its content is an under performer to algorithm and pulled down in the search results. This has a huge impact in multiple ways, which might consist organic traffic or Adsense revenue potential and other cases. A quick loading of websites can help you:
- Retain visitors
- Increase adsense earnings
- Improve SEO performance
- Generate more sales
Don't Let Images Slow Down Your Website: The Lazy Loading Solution
Lazy loading is the technique to render your images when the user actually needs it. For example, when a site loads, in the user’s view or screen, there is of course not the entire website, rather a part of it, most of the time the top part. So your machine dont need to load immediately all the images it has on the first loading right? Rather we can just show or render the images which is required in screen. So when the user tries to scroll down to see the other contents, then we can load the images at that part required.
This is how you can improve your site loading time dramatically as it doesnt have to take headache for all the images or heavy contents it has. This is called lazy loading to be precise.
- How Lazy Loading Works
Lazy loading just defers the images from loading until it is required, for example when they become visible while scrolling. Its also known as "above-the-fold" content. This is very helpful to reduce the loading time significantly.
Here's how lazy loading increases performance of the webpage:
Initial load: Only contents, resources and images required are loaded.
Scrolling event: When the user scrolls down, the images load progressively.
On-demand resource allocation: Those images never required, will never be loaded, because user might not have reached there. This helps improving performance by not loading unwanted resources.
- How to lazy load images?
Before html5, there was no support for lazy loading in older html versions. But in html5, we can add this directly to the img tags. Lets see a quick example on this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Loading Images</title>
</head>
<body>
<h1>Content above the fold (visible immediately)</h1>
<img src="placeholder.png" alt="Placeholder image" data-src="image1.jpg" loading="lazy" width="300" height="200">
<p>More content...</p>
<img src="placeholder.png" alt="Placeholder image" data-src="image2.jpg" loading="lazy" width="300" height="200">
</body>
</html>
Please note: here we are using an attribute loading=’lazy’ to tell browser to load these images as lazy. Also you need to put your image source path in data-src attribute as a requirement.
As this loading attribute is introduced in html5, most modern updated browsers will support it. But some older or mobile browsers might not support.
To keep a fallback scenario for those browsers which dont support lazy loading, you can add some scripts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Loading Images</title>
</head>
<body>
<h1>Content above the fold (visible immediately)</h1>
<img src="placeholder.png" alt="Placeholder image" data-src="image1.jpg" loading="lazy" width="300" height="200">
<p>More content...</p>
<img src="placeholder.png" alt="Placeholder image" data-src="image2.jpg" loading="lazy" width="300" height="200">
<script>
// Check if loading="lazy" is supported
if (!('loading' in HTMLImageElement.prototype)) {
const images = document.querySelectorAll('img[loading="lazy"]');
images.forEach(image => {
image.src = image.dataset.src;
});
}
</script>
</body>
</html>
You can check which browser it supports or doesnt in this link here:
- How you can measure performance
To measure how much difference you get after implementing lazy loading to your images, you can use your browser or chrome's DevTools comparing network activity before and after. Though it might seem bit complex to you, the performance improvement will also be visible in naked eye, you will see the site is loading lot faster and performance boosted than usual.
Here is a little guide to dig deeper if you are interested:
- Open DevTools and navigate to the Network tab.
- Load the images without lazy first and check the number of images or resources loaded and total page size
- No repeat the same procedure with lazy loading and check again. You should see fewer images loaded at first which are required in visible area of the page.
- The more you scroll down, the more images loads according to the scroll position. Thats smart, right?
So as images are loading as per scroll bar's position, its taking less time to respond and show content to the user.
Imagine, how much it helps for the users with slow internet or mobile consumers !!
- Alternatives?
Yeah, you might be thinking that, how would I use lazy loading for those old or mobile browsers. In that case, you can use some libraries like lazysizes.
Boost Website Performance: Lazy Load Images with Lazysizes Library
We can lazy load all the images using a new attribute introduced in html5 for img tag. Its a very simple way to do so. But this attribute isnt available for all the browsers actually. Most modern browsers support, but not the old or some mobile browsers. So alternatively we can take help of libraries like lazysizes.
The library called aFarkas/lazysizes is very simple and easy to use. Lets start with integrating the CDN in our html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Load Images with Lazysizes</title>
<!-- Lazysizes Library -->
<script src="https://afarkas.github.io/lazysizes/lazysizes.min.js"></script>
</head>
<body>
<!-- Your content goes here -->
</body>
</html>
Now, for the images which we want to lazy load, we will add a class named “lazyload” to each. Also, instead of using src attributes in img tags, we will use data-src attribute to assign the image source. Please see this example below:
<body>
<h1>Lazy Loading Images Example</h1>
<img src="path/to/placeholder.jpg" data-src="path/to/your-image1.jpg" class="lazyload" alt="Image 1">
<img src="path/to/placeholder.jpg" data-src="path/to/your-image2.jpg" class="lazyload" alt="Image 2">
<img src="path/to/placeholder.jpg" data-src="path/to/your-image3.jpg" class="lazyload" alt="Image 3">
</body>
Note: we can also added src attribute to have a fallback in case of error.
So our full code file should look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Load Images with Lazysizes</title>
<!-- Lazysizes Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js" async></script>
</head>
<body>
<h1>Lazy Loading Images Example</h1>
<img src="path/to/placeholder.jpg" data-src="path/to/your-image1.jpg" class="lazyload" alt="Image 1">
<img src="path/to/placeholder.jpg" data-src="path/to/your-image2.jpg" class="lazyload" alt="Image 2">
<img src="path/to/placeholder.jpg" data-src="path/to/your-image3.jpg" class="lazyload" alt="Image 3">
</body>
</html>
We are done with the implementation. Now it should lazy load all the images based on the class we have added to the tags.
Lazy Loading with Other Web Technologies
You can also do lazy loading in other technologies in any framework you are working in. All modern frameworks have many libraries available for lazy loading images. Lets see some quick example in react and vue:
- React Example
For react, there is a good package available called react-lazyload:
npm install react-lazyload
import LazyLoad from 'react-lazyload';
const ImageComponent = () => (
<LazyLoad height={200}>
<img src="path/to/image.jpg" alt="Lazy loaded image" />
</LazyLoad>
);
- Vue.js Example
In Vue.js, you can use vue-lazyload plugin to achieve the functionality. Here is example:
npm install vue-lazyload
import Vue from 'vue';
import VueLazyload from 'vue-lazyload';
Vue.use(VueLazyload);
<template>
<img v-lazy="'/path/to/image.jpg'" alt="Lazy loaded image">
</template>
Conclusion
Lazy loading is a technique which enables your website’s images to load when it is required. For example, if you are trying to load an webpage and it has 10 big images in different places, the browser doesnt need to render all the images at first load. Rather with this technique, the images are loaded when the user scrolls to the point where image is located. This technique not only saves the the loading time, also it increases performance drastically for the websites. It also helps to improve the website ranking in the search engines. So it is needless to say, how important it is to lazy load images for your own applications.
Thats all for this article today. Thanks for your visit for this post. Hope you like it. Please feel free to have some thoughts in the comments and like the article if you found it useful.
Wish you a happy day.
Comments