Home >Web Front-end >CSS Tutorial >5 Techniques for Lazy Loading Images to Boost Website Performance
In modern web applications, images have become one of the most commonly used content types. Although using background images can improve the visual effect of the application, too large image size will seriously affect the application performance.
Even after optimization, images may still take up a lot of space, causing users to wait too long. If users don't get the experience of fast access to content, they tend to lose patience and turn to other websites, so an efficient image loading scheme is crucial.
This article will introduce five lazy image loading methods to help you optimize your website and improve user experience. These methods are suitable for all types of images, including background images, inline images, and banner images.
Key Points
What is lazy loading?
Lazy image loading means asynchronously loading images on the website. Content can be loaded as needed after the page is fully loaded, or only if the image appears in the browser window. This means that if the user does not scroll down to the bottom, the image at the bottom of the page will not even be loaded, ultimately improving application performance.
For most websites, it is crucial to know how to enable lazy loading in HTML. For example, try browsing your favorite website with HD photos and you will soon find that the website is loading only a limited number of images. When you scroll down the page, the placeholder image is quickly replaced by the actual image.
For example, note the loader on Unsplash.com: Scrolling that part of the page into view triggers the placeholder replaced with a full resolution photo:
Why do you need to implement lazy loading of images?
Learning how to lazy load images is essential to optimize web performance, especially on pages with a lot of visual content. Here are some reasons why you should consider lazy loading images for your website:
1. Improve DOM loading time
2. Save bandwidth
Lazy loading of images helps improve website performance, but what is the best way to do it?
There is no perfect way.
If you are proficient in JavaScript, then implementing your own lazy loading solution should not be a problem. Nothing gives you more control than writing your own code.
Or, you can browse the web to find ways to do it, or join a discussion forum and share ideas. I did the same thing and found these five interesting ways.
1. Native lazy loading
When a user scrolls a web page, native lazy loading of images and iframes is a way to directly load content. You just need to add the loading="lazy"
attribute to your image and iframe.
<code class="language-html"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173897821515260.jpg" class="lazy" alt="5 Techniques for Lazy Loading Images to Boost Website Performance "> <iframe loading="lazy" src="content.html"></iframe></code>
As you can see, there is no need for JavaScript, nor dynamically replace the value of the src
attribute, just use normal HTML. This approach is a perfect example of adding lazy loads in HTML without any extra overhead.
'loading' property allows us to delay loading off-screen images and iframes until the user scrolls to the corresponding position on the page. "loading" can take any of the following three values:
This method is unmatched: it has almost no extra overhead and is a clean and simple way to lazy load images in HTML. However, while most mainstream browsers support the "loading" property well, some browsers still lack full support at the time of writing.
In-depth articles on the power of this HTML lazy loading image, including browser support workarounds, don't miss Addy Osmani's "Native image lazy-loading for the web!".
2. Use Intersection Observer API for lazy loading
Intersection Observer API is a modern interface that you can use to lazy load images and other content.
The following is MDN's introduction to this API:
Intersection Observer API provides a method to asynchronously observe the intersecting changes of target elements with ancestor elements or top-level document windows.
In other words, the Intersection Observer API monitors the intersection of one element with another asynchronously.
Denys Mishunov wrote an excellent tutorial on Intersection Observer and using it to lazy load images. Here is his solution:
Suppose you want to lazy load a picture library. The markings for each image are as follows:
<code class="language-html"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173897821515260.jpg" class="lazy" alt="5 Techniques for Lazy Loading Images to Boost Website Performance "> <iframe loading="lazy" src="content.html"></iframe></code>
Here, the path to the image is contained in the data-src
attribute, not the src
attribute. The reason is that using src
means the image will load immediately, which is not what you want.
In CSS, you can specify a min-height
value for each picture, such as 100px. This gives each image placeholder (img element without src
attribute) a vertical dimension:
<code class="language-html"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173897821665537.jpg" class="lazy" alt="5 Techniques for Lazy Loading Images to Boost Website Performance "></code>
Then, in the JavaScript documentation, you need to create a configuration object and register it with the intersectionObserver
instance:
<code class="language-css">img { min-height: 100px; /* more styles here */ }</code>
Finally, you can iterate over all the pictures and add them to this iterationObserver
instance:
<code class="language-javascript">// 创建配置对象:rootMargin和threshold是接口公开的两个属性 const config = { rootMargin: '0px 0px 50px 0px', threshold: 0 }; // 使用intersectionObserver实例注册配置对象 let observer = new IntersectionObserver(function(entries, self) { // 迭代每个条目 entries.forEach(entry => { // 只处理相交的图片。isIntersecting是接口公开的属性 if(entry.isIntersecting) { // 将图片路径从data-src复制到src的自定义函数 preloadImage(entry.target); // 图片现在已就位,停止观察 self.unobserve(entry.target); } }); }, config);</code>
The advantage of this solution is that it is easy to implement, efficient and intersecting. Observer undertakes most of the computing work.
In terms of browser support, all mainstream browsers except IE 11 and Opera Mini support the Intersection Observer API in their latest versions.
You can learn more about the Intersection Observer API and this implementation details in Denys' article.
3. Lozad.js
A quick and easy alternative to implementing lazy image loading is to let the JS library do most of the work for you.
Lozad.js is a high-performance, lightweight, and configurable lazy loader that uses pure JavaScript without any dependencies. It is an excellent tool for lazy loading JavaScript, pictures, videos and iframes when users scroll.
You can install Lozad using npm/Yarn and import it using the module packer of your choice:
<code class="language-javascript">const imgs = document.querySelectorAll('[data-src]'); imgs.forEach(img => { observer.observe(img); });</code>
<code class="language-bash">npm install --save lozad yarn add lozad</code>
Alternatively, you can simply download the library using CDN and add it to
at the bottom of the HTML page
lozad
Next, for the basic implementation, add class
<code class="language-javascript">import lozad from 'lozad';</code>
Finally, instantiate Lozad in your JS document:
<code class="language-html"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173897821885662.jpg" class="lazy" alt="5 Techniques for Lazy Loading Images to Boost Website Performance "></code>
You can find all the details of using the library in the Lozad GitHub repository.
Lozad is a great option if you don't want to know about the Intersection Observer API, or you're just looking for a quick implementation for a variety of content types.
4. Lazy loading with blurred picture effect