5 Techniques for Lazy Loading Images to Boost Website Performance
Feb 08, 2025 am 09:30 AMIn 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
- Image Lazy Loading improves website performance by loading pictures asynchronously. It will only be loaded after the visible content on the page is fully loaded or when the image appears in the browser window. This is especially important for users who use mobile devices and slow networks.
- Native lazy loading is an easy way to use HTML with almost no extra overhead, but not all browsers support this feature. The Intersection Observer API is another easy to implement and effective method, but not all browsers also support it.
- JavaScript libraries such as Lozad.js and Yall.js can quickly and easily implement lazy loading of images, videos, and iframes. They use the Intersection Observer API, but browser compatibility needs to be considered.
- Similar to Medium websites, while lazy loading high-resolution pictures, first display blurred low-resolution pictures, which can get a good visual effect. This can be achieved in a variety of ways, such as the high-performance method proposed by Craig Buckler, which also supports retinal screens.
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
- If your website uses JavaScript to display content or provides some functionality to the user, it is crucial to quickly load the DOM. The script usually starts running after the DOM is fully loaded. On a website with a large number of images, lazy loading (or asynchronously loading images) may determine whether the user will continue to browse or leave your website.
2. Save bandwidth
- Since most lazy loading solutions only load images when the user scrolls to a location where the image is visible in the window, these images will never be loaded if the user never reaches that location. This means a lot of bandwidth savings can be saved, which is very beneficial for most users, especially those using mobile devices and slow networks.
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="/static/imghw/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></pre>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:
- lazy: Very suitable for lazy loading
- eager: Instructs the browser to load the specified content immediately
- auto: Leave the option to the browser whether to load lazily.
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="/static/imghw/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></pre>Here, the path to the image is contained in the
data-src
attribute, not thesrc
attribute. The reason is that usingsrc
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 withoutsrc
attribute) a vertical dimension:<img src="/static/imghw/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 " /></pre>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>Finally, you can iterate over all the pictures and add them to this
iterationObserver
instance:// 創(chuàng)建配置對象: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的自定義函數(shù) preloadImage(entry.target); // 圖片現(xiàn)在已就位,停止觀察 self.unobserve(entry.target); } }); }, config);</pre>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
lozad.js Lazy loading of JavaScript library 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>npm install --save lozad yarn add lozad</pre>Alternatively, you can simply download the library using CDN and add it to
</pre>
at the bottom of the HTML page
to the resource in the tag:lozad
Next, for the basic implementation, add classimport lozad from 'lozad';</pre>Finally, instantiate Lozad in your JS document:
<img src="/static/imghw/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 " /></pre>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="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.
Blurry placeholder pictures on Medium website High resolution lazy loading pictures on Medium website 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:
- Performance: Only 463 bytes of CSS and 1007 bytes of compressed JavaScript code.
- Supports retinal screen.
- No dependency: no jQuery or other libraries and frameworks are required.
- Progressively enhanced to deal with legacy browser and JavaScript failures.
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="/static/imghw/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></pre>Next, to lazy load a simple img element, you just need to do the following in the tag:
<img src="/static/imghw/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 " /></pre>Please note the following points:
- You add the class
lazy
to the element.
The value of src
is a placeholder image.- The path of the image you want to lazy load is in the
data-src
property.
The following are the advantages of Yall.js:
- Get excellent performance using the Intersection Observer API.
- Excellent browser support (it goes back to IE11).
- No other dependencies are required.
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?
- Improving website performance
- Speed ??up initial page rendering and reduced bandwidth usage.
- Enhance the user experience.
- Reduce server load and improve overall efficiency of web applications.
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="/static/imghw/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></pre>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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

TheCSSPaintingAPIenablesdynamicimagegenerationinCSSusingJavaScript.1.DeveloperscreateaPaintWorkletclasswithapaint()method.2.TheyregisteritviaregisterPaint().3.ThecustompaintfunctionisthenusedinCSSpropertieslikebackground-image.Thisallowsfordynamicvis

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
