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.
<img src="https://img.php.cn/upload/article/000/000/000/173897821515260.jpg" alt="5 Techniques for Lazy Loading Images to Boost Website Performance " /> <iframe loading="lazy" src="content.html"></iframe></pre>Copy after login
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:
<img src="https://img.php.cn/upload/article/000/000/000/173897821515260.jpg" alt="5 Techniques for Lazy Loading Images to Boost Website Performance " /> <iframe loading="lazy" src="content.html"></iframe></pre>Copy after login
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:
<img src="https://img.php.cn/upload/article/000/000/000/173897821665537.jpg" alt="5 Techniques for Lazy Loading Images to Boost Website Performance " /></pre>Copy after login
Then, in the JavaScript documentation, you need to create a configuration object and register it with the intersectionObserver
instance:
img { min-height: 100px; /* more styles here */ }</pre>Copy after login
Finally, you can iterate over all the pictures and add them to this iterationObserver
instance:
// 创建配置对象: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);</pre>Copy after login
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:
const imgs = document.querySelectorAll('[data-src]'); imgs.forEach(img => { observer.observe(img); });</pre>Copy after login
npm install --save lozad yarn add lozad</pre>Copy after login
Alternatively, you can simply download the library using CDN and add it to </pre>
at the bottom of the HTML page
lozad
Next, for the basic implementation, add class
import lozad from 'lozad';</pre>Copy after login
Finally, instantiate Lozad in your JS document:
<img src="https://img.php.cn/upload/article/000/000/000/173897821885662.jpg" alt="5 Techniques for Lazy Loading Images to Boost Website Performance " /></pre>Copy after login
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
<script></code>标签中:</p> <pre class="brush:php;toolbar:false"><code class="language-html"><script src="https://cdn.jsdelivr.net/npm/lozad"></script>If you are a Medium reader, you must have noticed how the site loads the main image in the post. The first thing you see is a blurred low-resolution copy of the image, and its high-resolution version is lazy loading:
You can get similar effects when lazy loading images in HTML by using CSS and JavaScript.
You can add this fun blur effect to your image in a number of ways.
My favorite method is the Craig Buckler method. Here are all the advantages of this solution:
You can read all the relevant information in "How to Build Your Own Progressive Image Loader" and download the code in the project's GitHub repository.
5. Yall.js
Yall.js is a feature-rich JavaScript library that uses the Intersection Observer API to lazy load JavaScript while users scroll. It supports pictures, videos, iframes, and cleverly falls back to traditional event handler technology when necessary.
When you include Yall in your document, you need to initialize it as follows:
<img src="https://img.php.cn/upload/article/000/000/000/173897821515260.jpg" alt="5 Techniques for Lazy Loading Images to Boost Website Performance " /> <iframe loading="lazy" src="content.html"></iframe></pre>Copy after login
Next, to lazy load a simple img element, you just need to do the following in the tag:
<img src="https://img.php.cn/upload/article/000/000/000/173897821665537.jpg" alt="5 Techniques for Lazy Loading Images to Boost Website Performance " /></pre>Copy after login
Please note the following points:
lazy
to the element. src
is a placeholder image. data-src
property. The following are the advantages of Yall.js:
To learn more about what Yall.js can offer and more complex implementations, feel free to check out the project page on GitHub.
Conclusion
Here are five lazy loading methods you can start experimenting and testing in your project. Understanding how to lazy load images is a valuable skill for any web developer. You can learn more about image optimization by joining this SitePoint forum or share your expertise with others.
Frequently Asked Questions about Lazy Picture Loading
What is lazy loading of pictures?
Lazy loading is a web development technology used to improve web page performance by lazy loading certain elements, such as images, until they are needed. Lazy image loading means that the image is loaded only when it enters the user's window or is visible on the web page, rather than loading all images immediately when the page is initially rendered.
What are the benefits of lazy loading pictures?
How to lazy load images in HTML?
To add lazy loading to images in HTML, you can use the "loading" property. The "loading" property is a standard HTML property that allows you to control when images should be loaded. To enable HTML lazy loading images, set the value of the "loading" property to "lazy" and add it to the img element. This will tell the browser to load the image only when it is about to enter the window. Here is an example:
<img src="https://img.php.cn/upload/article/000/000/000/173897821515260.jpg" alt="5 Techniques for Lazy Loading Images to Boost Website Performance " /> <iframe loading="lazy" src="content.html"></iframe></pre>Copy after login
Is it okay to load the picture lazy?
Yes, using lazy loading image HTML in web development is considered a beneficial practice for the following reasons. It speeds up initial page rendering and improves user experience by delaying loading of non-essential image loading. This approach saves bandwidth and is beneficial for users with limited data plans or slower internet connections. Additionally, it positively affects search engine optimization (SEO) by increasing page loading speed and conforms to the principle of incremental enhancement. By reducing perceived latency and providing visual cues during loading, lazy loading helps provide a smoother and more efficient browsing experience, especially on mobile devices.
How to know if the image is lazy to load?
To confirm that you have correctly implemented how to lazy load images in HTML, you can check the HTML source code or use browser developer tools. By right-clicking on the image and selecting Check or Check Elements, you can check the img element representing the image in the Developer Tools panel. Find if the "loading" attribute exists in the img element. If the "loading" property is set to "lazy", it means that the image has been configured to be lazy. Using the browser developer tool, you can quickly determine the lazy loading status of the image by checking the properties of the image.
How to use JavaScript to achieve lazy image loading?
To use JavaScript to achieve lazy image loading, 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 load content on demand by monitoring when elements enter the window and load them at that moment.
Will lazy image loading affect SEO?
Yes, lazy image loading can have a positive impact on SEO. By increasing page loading time and reducing the amount of data that needs to be loaded initially, lazy loading can help your website get better rankings in search engine results. Faster page speeds are a ranking factor known to search engines like Google, and lazy loading can facilitate this by ensuring that your website images don't slow down 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" attributes in the <img alt="5 Techniques for Lazy Loading Images to Boost Website Performance" >
and <iframe></iframe>
tags. This method is simple and does not require additional JavaScript. On the other hand, lazy loading based on JavaScript (usually implemented using libraries such as Lozad.js or Intersection Observer API) provides greater flexibility and customization.
Is there any disadvantage of lazy loading of pictures?
The main disadvantage is that the image may delay loading when the user scrolls down the page. Additionally, some older browsers may not support lazy loading.
Can I lazy load pictures in WordPress?
Yes, you can easily lazy load pictures 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 achieve lazy loading without any encoding.
The above is the detailed content of 5 Techniques for Lazy Loading Images to Boost Website Performance. For more information, please follow other related articles on the PHP Chinese website!