How to Use Intersection Observer API for Lazy Loading Images

魔法使者 2021-04-14 ⋅ 19 阅读

In this digital age, where web pages are becoming more image-heavy, it's crucial to optimize the loading process for a better user experience. One effective technique for improving loading times is lazy loading images using the Intersection Observer API. In this blog post, we will dive into the details of how to implement lazy loading using this API.

What is Lazy Loading?

Lazy loading is a technique used to defer the loading of non-critical resources, such as images, until they are about to be scrolled into view. This means that only the images that a user sees on the screen are loaded, reducing the initial load time.

Intersection Observer API

The Intersection Observer API is a web API that allows you to asynchronously observe changes in the intersection of a target element with an ancestor element or with the viewport. It provides a way to determine when an element enters or exits the viewport or when it intersects with another element.

Implementing Lazy Loading with Intersection Observer API

To implement lazy loading using the Intersection Observer API, follow these steps:

  1. First, make sure you have an <img> element with a data-src attribute that contains the URL of the image to be loaded.
<img src="placeholder.jpg" data-src="image.jpg" alt="Lazy Loaded Image">
  1. Initialize an Intersection Observer instance by passing a callback function and an options object to the constructor. In the callback function, you can specify the actions to be taken when the observed element enters or exits the viewport.
<script>
  const images = document.querySelectorAll('img[data-src]');

  const options = {
    root: null,
    rootMargin: '0px',
    threshold: 0.1
  };

  const handleIntersection = (entries, observer) => {
    entries.forEach((entry) => {
      if (entry.intersectionRatio > 0) {
        const img = entry.target;
        img.src = img.dataset.src;
        observer.unobserve(img);
      }
    });
  };

  const observer = new IntersectionObserver(handleIntersection, options);

  images.forEach((img) => {
    observer.observe(img);
  });
</script>
  1. Here, we are selecting all <img> elements with a data-src attribute. Then, we define the options for the Intersection Observer, including the threshold at which the intersection will be considered.

  2. In the handleIntersection callback, we check if the observed element's intersectionRatio is greater than 0. If so, it means the element is visible on the screen, and we can set the src attribute to the data-src value, effectively loading the image.

  3. Finally, we call the observe() method for each image element to start observing changes in their intersection with the viewport.

That's it! You have successfully implemented lazy loading images using the Intersection Observer API. Now, as the user scrolls, images will only be loaded when they are about to become visible, improving the page's loading time and user experience.

Lazy loading is an effective technique for optimizing web page loading times, especially when dealing with large image files. By using the Intersection Observer API, you can implement lazy loading seamlessly and ensure a smooth user experience.


全部评论: 0

    我有话说: