Images have become one of the most used types of content in modern web applications. Although using background images improves the application’s look and feel, increasing image sizes can significantly impact application performance.
Even when properly optimized, images can weigh quite a bit and keep users waiting to access content on your website. Often, they get impatient and navigate somewhere else unless you come up with a solution to image loading that doesn’t interfere with the perception of speed.
In this article, you’ll learn about five approaches to lazy loading images that you can add to your web optimization toolkit to improve the user experience on your website. You can use these methods to lazy load various image types in your application including background images, inline images, and banner images.
Key Takeaways
- Faster Page Loads: Lazy loading images helps improve your website’s speed by loading only the images that are visible in the user’s viewport.
- Better User Experience: Lazy loading enhances the browsing experience, especially for users on slower connections or mobile devices by reducing load times,
- Bandwidth Savings: Images are only loaded if needed, saving bandwidth and reducing data usage for both users and servers.
- Simple Implementation: You can easily implement lazy loading using the HTML “loading” attribute or more advanced methods like the Intersection Observer API.
- SEO Benefits: Faster load times from lazy loading can contribute to better search engine rankings, helping your site perform better in search results.
What Is Lazy Loading?
Lazy loading images means loading images on websites asynchronously. You can lazy load content on scroll after the above-the-fold content is fully loaded or conditionally when it only needs to 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, ultimately improving the application performance.
Understanding how to enable lazy loading in HTML is essential for web developers as most websites require this approach. For example, try browsing your favorite online hunting ground for high-res photos, and you’ll soon realize that the website loads only a limited number of images. As you scroll down the page, the placeholder image quickly fills up with actual image for preview.
For instance, notice the loader on Unsplash.com: scrolling that portion of the page into view triggers the replacement of a placeholder with a full-res photo:
Why You Should Implement Lazy Loading for Images?
Understanding how to lazy load images is crucial for optimizing web performance, especially on pages with heavy visual content. Here are a couple of excellent reasons why you should consider lazy loading images for your website:
1. Improves DOM Loading Time
- If your website uses JavaScript to display content or provide some kind of functionality to users, loading the DOM quickly becomes critical. It’s common for scripts to wait until the DOM has completely loaded before they start running. On a site with a significant number of images, lazy loading — or loading images asynchronously — could make the difference between users staying or leaving your website.
2. Limited Bandwith Use
- Since most lazy loading solutions work by loading images only if the user scrolls to the location where images would be visible inside the viewport, those images will never be loaded if users never get to that point. This means considerable bandwidth savings, for which most users, especially those accessing the Web on mobile devices and slow connections, will be thanking you.
Well, lazy loading images help with website performance, but what’s the best way to do it?
There’s no perfect way.
If you live and breathe JavaScript, implementing your own lazy loading solution shouldn’t be an issue. Nothing gives you more control than coding something yourself.
Alternatively, you can browse the Web for viable approaches or join a discussion Forum and share ideas. I did just that and came across these five interesting techniques.
1. Native Lazy Loading
Native lazy loading of images and iframes is a straightforward method to lazy load content when a user scrolls the web page. You just need to add the loading=”lazy” attribute to your images and iframes.
<img src="myimage.jpg" loading="lazy" alt="..." />
<iframe src="content.html" loading="lazy"></iframe>
As you can see, no JavaScript, no dynamic swapping of the src attribute’s value, just plain old HTML. This method is a perfect example of how to add lazy loading in HTML without any additional overhead.
The “loading” attribute gives us the option to delay off-screen images and iframes until users scroll to their location on the page. loading can take any of these three values:
- lazy: Works great for lazy loading
- eager: Instructs the browser to load the specified content right away
- auto: Leaves the option to lazy load or not to lazy load up to the browser.
This method has no rivals: it has zero overhead, and it’s a clean and simple way to lazy load images in HTML. However, although most major browsers have good support for the “loading” attribute, some browsers still lack full support as of the time of writing.
For an in-depth article on this awesome feature for HTML lazy load images, including browser support workarounds, don’t miss Addy Osmani’s “Native image lazy-loading for the web!“.
2. Lazy Loading Using the Intersection Observer API
The Intersection Observer API is a modern interface that you can leverage for lazy loading images and other content.
Here’s how MDN introduces this API:
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.
In other words, Intersection Observer API watches the intersection of one element with another asynchronously.
Denys Mishunov has a great tutorial both on the Intersection Observer and on lazy loading images using it. Here’s what his solution looks like.
Let’s say you’d like to lazy load an image gallery. The markup for each image would look like this:
<img data-src="image.jpg" alt="test image">
Here, the path to the image is contained inside a data-src attribute, not a src attribute. The reason is that using src means the image would load right away, which is not what you want.
In the CSS, you can give each image a min-height value, let’s say 100px. This gives each image placeholder (the img element without the src attribute) a vertical dimension:
img {
} min-height: 100px;
/* more styles here */
Then, in the JavaScript document, you need to create a config object and register it with an intersectionObserver instance:
// create config object: rootMargin and threshold
// are two properties exposed by the interface
const config = {
rootMargin: '0px 0px 50px 0px',
threshold: 0
};
// register the config object with an instance
// of intersectionObserver
let observer = new intersectionObserver(function(entries, self) {
// iterate over each entry
entries.forEach(entry => {
// process just the images that are intersecting.
// isIntersecting is a property exposed by the interface
if(entry.isIntersecting) {
// custom function that copies the path to the img
// from data-src to src
preloadImage(entry.target);
// the image is now in place, stop watching
self.unobserve(entry.target);
}
});
}, config);
Finally, you can iterate over all of your images and add them to this iterationObserver instance:
const imgs = document.querySelectorAll('[data-src]');
imgs.forEach(img => {
observer.observe(img);
});
The merits of this solution are that it’s a breeze to implement, it’s effective, and it has the intersection. Observer does the heavy lifting in terms of calculations.
When it comes to browser support, all the major browsers support Intersection Observer API in their latest versions, except IE 11 and Opera Mini.
You can learn more about the Intersection Observer API and the details of this implementation in Denys’s article.
3. Lozad.js
A quick and easy alternative for implementing lazy loading of images is to let a JS library do most of the job for you.
Lozad.js is a highly performant, light, and configurable lazy loader that uses pure JavaScript with no dependencies. It’s an excellent tool for lazy loading JavaScript when a user scrolls images, videos, and iframes.
You can install Lozad with npm/Yarn and import it using your module bundler of choice:
npm install --save lozad
yarn add lozad
import lozad from 'lozad';
Alternatively, you can simply download the library using a CDN and add it to the bottom of the HTML page in a < script> tag:
<script src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>
Next, for a basic implementation, add the class lozad to the asset in your markup:
<img class="lozad" data-src="img.jpg">
Finally, instantiate Lozad in your JS document:
const observer = lozad();
observer.observe();
You’ll find all the details of using the library on the Lozad GitHub repository.
If you don’t want to learn about the Intersection Observer API or you’re simply looking for a fast implementation that applies to a variety of content types, Lozad is a great choice.
4. Lazy Loading with Blurred Image Effect
If you’re a Medium reader, you have certainly noticed how the site loads the main image inside a post. The first thing you see is a blurred, low-resolution copy of the image, while its high-res version is being lazy loaded:
You can achieve a similar effect when you lazy load images in HTML by using CSS and JavaScript together.
You can add lazy load to images with this interesting blurring effect in a number of ways.
My favorite technique is by Craig Buckler. Here’s all the goodness of this solution:
- Performance: Only 463 bytes of CSS and 1,007 bytes of minified JavaScript code.
- Support for retina screens.
- Dependency-free: No jQuery or other libraries and frameworks are required.
- Progressively enhanced to counteract older browsers and failing JavaScript.
You can read all about it in How to Build Your Own Progressive Image Loader and download the code on the project’s GitHub repo.
5. Yall.js
Yall.js is a feature-packed JavaScript library that uses Intersection Observer API for lazy loading JavaScript when a user scrolls. It supports images, videos, iframes, and smartly falls back on traditional event handler techniques where necessary.
When including Yall in your document, you need to initialize it as follows:
<script src="yall.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", yall);
</script>
Next, to lazy load a simple img element, all you need to do in your markup is:
<img
class="lazy"
src="placeholder.jpg"
data-src="image-to-lazy-load.jpg"
alt="Alternative text to describe image."
>
Note the following:
- You add the class lazy to the element.
- The value of src is a placeholder image.
- The path to the image you want to lazy load is inside the data-src attribute.
Here are the benefits of Yall.js:
- Great performance with the Intersection Observer API.
- Fantastic browser support (it goes back to IE11).
- No other dependencies are necessary.
To learn more about what Yall.js can offer and for more complex implementations, feel free to check out the project’s page on GitHub.
Conclusion
And there you have it — five ways of lazy loading images you can start to experiment with and test out in your projects. Understanding how to lazy load images is a valuable skill for any web developer., you can learn more techniques or share your expertise with others by joining this SitePoint forum on image optimization.
FAQs About Lazy Loading Images
What Is Lazy Loading Images?
Lazy loading is a web development technique used to improve the performance of web pages by deferring the loading of certain elements, such as images until they are needed. Lazy loading images means that images are loaded only when they enter the user’s viewport or become visible on the web page, rather than loading all images as soon as the page is initially rendered.
What Are the Benefits of Lazy Loading Images?
- Improved website performance
- Faster initial page rendering, and reduced bandwidth usage.
- Enhance the user experience.
- Reduce the server load and improve the overall efficiency of your web application.
How to Lazy Load Images in HTML?
To add lazy load to images in HTML, you can use the “loading” attribute. The “loading” attribute is a standard HTML attribute that allows you to control when an image should be loaded. To enable HTML lazy load images, add the “loading” attribute with the value “lazy” to the img element. This tells the browser to load the image only when it is about to enter the viewport. Here’s an example:
<img src="image.jpg" alt="Description" loading="lazy">
Is Lazy Loading Images Good?
Yes, using lazy load images HTML is considered a beneficial practice in web development for several reasons. It enhances page loading speed by deferring non-essential image loading, resulting in faster initial page rendering and improved user experience. This approach conserves bandwidth, making it advantageous for users with limited data plans or slower internet connections. Additionally, it positively impacts search engine optimization (SEO) by boosting page loading speed, and it aligns with the principles of progressive enhancement. By reducing perceived wait times and providing visual cues during loading, lazy loading contributes to a smoother and more efficient browsing experience, particularly on mobile devices.
How Do You Know If an Image Is Lazy Loaded?
To confirm if you’ve correctly implemented how to lazy load images HTML, you can inspect the HTML source code or use browser developer tools. By right-clicking on the image and selecting “Inspect” or “Inspect Element,” you can examine the img element representing the image in the developer tools panel. Look for the presence of the “loading” attribute within the img element. If the “loading” attribute is set to “lazy,” it indicates that the image is configured for lazy loading. Using browser developer tools, you can quickly ascertain the lazy loading status of images by examining their attributes.
How Can I Implement Lazy Loading for Images Using JavaScript?
To implement lazy loading for images using JavaScript, you can use libraries like Lozad.js or Yall.js, or you can write your own custom solution using the Intersection Observer API. These libraries allow you to lazy load content on scroll by monitoring when elements enter the viewport and loading them only at that moment.
Does Lazy Loading Images Affect SEO?
Yes, lazy loading images can positively affect SEO. By improving page load times and reducing the amount of data that needs to be loaded initially, lazy loading can help your website rank better in search engine results. Faster page speeds are a known ranking factor for search engines like Google, and lazy loading can contribute to this by ensuring that your website’s images don’t slow down the overall performance.
What Is the Difference Between Native Lazy Loading and JavaScript-Based Lazy Loading?
Native lazy loading relies on the browser’s built-in support for the “loading” attribute in <img> and <iframe> tags. This method is simple and requires no additional JavaScript. On the other hand, JavaScript-based lazy loading, often implemented using libraries like Lozad.js or the Intersection Observer API, offers more flexibility and customization.
Are There Any Downsides to Lazy Loading Images?
The main downside is that images might load with a slight delay as the user scrolls down the page. Also, some older browsers might not support lazy loading.
Can I Lazy Load Images in WordPress?
Yes, you can easily lazy load images in WordPress. Many themes now support native lazy loading by default, but you can also use plugins like “Lazy Load by WP Rocket” or “Smush” to implement lazy loading without any coding.
Maria Antonietta Perna is a teacher and technical writer. She enjoys tinkering with cool CSS standards and is curious about teaching approaches to front-end code. When not coding or writing for the web, she enjoys reading philosophy books, taking long walks, and appreciating good food.