Lazy Loading (懒加载) is a technique used in web development to defer the loading of non-critical resources until they are needed. This can improve the performance of web pages by reducing the initial load time and bandwidth usage.
Why Use Lazy Loading?
- Improved Performance: Reduces the amount of data that needs to be loaded initially, resulting in faster page load times.
- Enhanced User Experience: Reduces the time it takes for the page to become interactive, leading to a smoother user experience.
- Bandwidth Savings: Decreases the amount of bandwidth required for page loads, which is especially beneficial for users with slow or limited internet connections.
How Does Lazy Loading Work?
Lazy loading works by deferring the loading of images, videos, and other resources until they are about to enter the viewport. This can be achieved in several ways:
- Intersection Observer API: Allows you to specify a callback that is executed when an element enters the viewport.
- Scroll event: Detects when an element comes into view as the user scrolls.
- Visibility API: Determines whether an element is visible in the viewport.
Lazy Loading Techniques
- Images: Load images only when they are about to enter the viewport.
- Videos: Start playing videos only when the user scrolls to the relevant section.
- Other Resources: Lazy load scripts, stylesheets, and other resources that are not critical for the initial rendering of the page.
Example
Here's an example of how to implement lazy loading for images using the Intersection Observer API:
const lazyImages = document.querySelectorAll('img[data-src]');
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const image = entry.target;
image.src = image.dataset.src;
observer.unobserve(image);
}
});
});
lazyImages.forEach(image => {
imageObserver.observe(image);
});
For more information on implementing lazy loading, you can refer to our Lazy Loading Guide.
Lazy Loading Concept