Home  >  Article  >  Web Front-end  >  Implementing lazy loading function based on JavaScript

Implementing lazy loading function based on JavaScript

WBOY
WBOYOriginal
2023-08-08 10:49:431428browse

Implementing lazy loading function based on JavaScript

Implementing lazy loading function based on JavaScript

Lazy loading is a commonly used front-end optimization technology designed to improve the loading speed and user experience of the page. Through lazy loading, certain resources in the page (such as images, videos, texts, etc.) can be delayed until the user needs or is about to browse them, thus reducing the network request and page loading during the first load. time.

In this article, we will introduce how to use JavaScript to implement the lazy loading function and provide code examples.

  1. The principle of lazy loading

The principle of lazy loading is to listen to page scroll events or other interactive behaviors. When the page scrolls to a specific position or the user operates to load resources, to the location, then load the resource.

  1. Steps to implement lazy loading

2.1 First, you need to add a specific identifier to the element that needs to be lazy loaded. It can be a class attribute or a data attribute, etc. For example, add a class attribute of "lazy" to the image that needs to be loaded lazily.

example

The src attribute is placeholder Picture, the data-src attribute is the real picture address.

2.2 After the page is loaded, use JavaScript to obtain all elements with lazy loading identifiers and bind a scroll event.

<script></script>

document.addEventListener("DOMContentLoaded", function() {
  var lazyImages = document.querySelectorAll(".lazy");

  // 绑定滚动事件
  window.addEventListener("scroll", lazyLoad);
  window.addEventListener("resize", lazyLoad);
  
  // 加载初始屏幕可见区域内的图片
  lazyLoad();
  
  function lazyLoad() {
    lazyImages.forEach(function(img) {
      if (isInViewport(img)) {
        img.src = img.getAttribute("data-src");
        img.classList.remove("lazy");
      }
    });

    // 删除滚动事件绑定,减少性能消耗
    if (lazyImages.length === 0) {
      window.removeEventListener("scroll", lazyLoad);
      window.removeEventListener("resize", lazyLoad);
    }
  }

  // 检查元素是否在可视区域内
  function isInViewport(element) {
    var rect = element.getBoundingClientRect();
    return (
      rect.bottom >= 0 &&
      rect.right >= 0 &&
      rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.left <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

});

  1. Test the lazy loading effect

In the above code, we use two event listeners (scroll and resize) to monitor page scrolling and window size changes. Every time it detects scrolling or window size changes, the lazyLoad function will be called.

The lazyLoad function traverses all lazy loading images and checks whether they are within the visible area. If so, assign the data-src attribute to src, that is, load the real image, and remove the class attribute to lazy. Use the above isInViewport function to determine whether the element is within the visible area.

  1. Summary

Lazy loading is a very practical front-end technology, which not only improves the performance of web pages, but also improves the user experience. Implementing the lazy loading function through JavaScript can greatly reduce page loading time and network requests.

I hope this article will help you understand the implementation method of lazy loading, and I hope you can make corresponding modifications and optimizations according to your own project needs. I wish you good results when using lazy loading techniques!

Code sample completed.

The above is the detailed content of Implementing lazy loading function based on JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn