JS implements lazy loading on images and scroll events

Record the lazy loading of images and page scrolling

1. Use Intersection Observer API for lazy loading of images

The Intersection Observer API is a JavaScript API that allows developers to observe intersection changes of elements with a specific ancestor or viewport. It tracks the visibility of the target element and notifies the developer when the element enters or leaves view. It's great for lazy loading images because it notifies us when an image enters or leaves the viewport, allowing us to load images as needed. It runs on a separate thread and does not block the main JavaScript thread. The API is not limited to images, but can be used to lazy load any content such as videos, iframes or even generated page sections.

Multiple Intersection Observers can observe different elements on the same page at the same time. For example, let's say you have a page with multiple images on it, and you want to lazy load the images as the user scrolls down the page. Here's how to implement lazy loading using the Intersection Observer API and native JavaScript. To get started, make sure you have a basic HTML structure that contains a data-src attribute with an img tag specifying the actual source URL of the image. We will use data-src to store the URL of the image instead of using the traditional src attribute to implement lazy loading of images.

<!DOCTYPE html>
<html>
<head>
 <title>Lazy Loading Images</title>
</head>
<body>
 <h1>Lazy Loading Images Example</h1>
 <img class="lazy" data-src="image1.jpg" alt="Image 1">
 <img class="lazy" data-src="image2.jpg" alt="Image 2">
 <!-- Add more images with the "lazy" class and "data-src" attribute -->
</body>
</html>

In our JavaScript code, we will create an instance of Intersection Observer and specify a callback function that will be fired whenever the observed element enters or leaves the viewport.

// Get all elements with the "lazy" class
const lazyImages = document.querySelectorAll(".lazy");
// Create a new Intersection Observer
const observer = new IntersectionObserver((entries, observer) => {
    
    
 entries.forEach((entry) => {
    
    
  if (entry.isIntersecting) {
    
    
   // Load the image when it comes into the viewport
   entry.target.src = entry.target.dataset.src;
   observer.unobserve(entry.target); // Unobserve the image after it's loaded
  }
 });
});
// Observe each lazy image
lazyImages.forEach((image) => {
    
    
 observer.observe(image);
});

In the above code, first use document.querySelectorAll(".lazy") to select all elements with "lazy" class. We then create a new Intersection Observer instance, passing in a callback function that fires whenever the observed element (in this case the lazy-loaded image) enters or exits the viewport. When an image is observed and entered into the viewport (that is, entry.isIntersecting is true), we set its src attribute to the value of data-src, which holds the actual image URL. This operation triggers lazy loading of images. We then call observer.unobserve(entry.target) to stop observing the image once it has finished loading to optimize performance.

2. Lazy loading of content on scroll events

The scroll event-based approach enables highly customized lazy loading implementations. You have complete control over when and how content loads, making it suitable for scenarios where you need to perform specific tasks or transitions when an element is visible. Scroll events are a feature of JavaScript supported by all modern browsers. This means you don't have to worry about compatibility issues.

For single-page applications, where content loads as the user navigates the site, it may be more intuitive to use scroll events. Unlike the Intersection Observer API, which is best suited for images and specific elements, scroll event-based lazy loading provides more flexibility. You can apply this to any content or complex component that may not fit into the "in view" concept. Let's look at an example. Here you will again have a basic HTML structure with the elements you want to lazily load. However, this time we don't need special attributes like data-src.

<!DOCTYPE html>
<html>
<head>
 <title>Lazy Loading Content on Scroll</title>
</head>
<body>
 <h1>Lazy Loading Content Example</h1>
 <div class="lazy-content">
  <p>Some content to be lazily loaded...</p>
 </div>
 <div class="lazy-content">
  <p>More content to be lazily loaded...</p>
 </div>
 <!-- Add more elements with the "lazy-content" class -->
</body>
</html>

In our JavaScript code, you will have a function isElementInViewport(element) which will check if an element is in the viewport and then define a lazyLoadContent() function that uses document.querySelectorAll(".lazy-content") Iterate through all elements with class "lazy-content".

// Function to check if an element is in the viewport
function isElementInViewport(element) {
    
    
 const rect = element.getBoundingClientRect();
 return (
  rect.top >= 0 &&
  rect.left >= 0 &&
  rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
  rect.right <= (window.innerWidth || document.documentElement.clientWidth)
 );
}
// Function to lazily load content
function lazyLoadContent() {
    
    
 const lazyContentElements = document.querySelectorAll(".lazy-content");
 lazyContentElements.forEach((element) => {
    
    
  if (isElementInViewport(element)) {
    
    
   // Add your logic to load the content for the element here
   element.classList.add("loaded");
  }
 });
}
// Attach the lazyLoadContent function to the scroll event
window.addEventListener("scroll", lazyLoadContent);
// Call the function initially to load the visible content on page load
lazyLoadContent();

For each element, it checks if it is in the viewport using isElementInViewport(element), and if true, loads the content of that element. In this example, we just add a class name "loaded" to the element, but you can customize this part according to your use case. We then attach the lazyLoadContent() function to the scroll event using window.addEventListener("scroll", lazyLoadContent). This ensures that the function is called every time the user scrolls the page. Additionally, we call lazyLoadContent() when the page loads to load visible content.

Guess you like

Origin blog.csdn.net/weixin_45324044/article/details/132402938