The first two chapters describe two ways to implement lazy loading. The last one is implemented through a new API called IntersectionObserver. However, the API has compatibility issues and is supported by Chrome 51+. For details, go to MDN.

1. Implementation principle

  • IntersectionObserverintroduce

IntersectionObserver can asynchronously observe the way in which a target element intersects with its ancestor element or top-level document window (viewport). That is, it helps us determine if an element is present in the viewport. There are only two attributes used:

  • IntersectionObserver.observe():IntersectionObserverStart listening for a target element
  • isIntersectingAttribute: Determines whether the element is present in the viewport;
  • Realize the principle of

According to the two attributes introduced above, we can traverse each IMG element, and then monitor each element. Finally, according to the isIntersecting attribute, we can judge whether the element appears in the viewport and decide whether to load it or not.

2. Implementation

  • HTMLThe structure andCSSstyle
<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0"> <title>Document</title> <style> img { height: 450px; display: block; margin-bottom: 20px; } </style> </head> <body> <! -- The image address is stored in the custom attribute data-src --> <img data-src="./img-loop/img/1.jpg" alt="Lazy loading 1" />
  <img data-src="./img-loop/img/2.png" alt=Lazy loading 2 />
  <img data-src="./img-loop/img/3.jpg" alt="Lazy loading 3" />
  <img data-src="./img-loop/img/4.jpg" alt="Lazy loading 4" />
  <img data-src="./img-loop/img/5.jpg" alt="Lazy loading 5" />
</body>
</html>
Copy the code
  • JScode
      document.addEventListener("DOMContentLoaded", () = > {if ("IntersectionObserver" in window) {
          const imgs = document.getElementsByTagName("img"); Const imageObserve = new IntersectionObserver((entries) => {entries.foreach ((entry) => {// Use this property to determine whether the element is present in the viewportif(entry.isintersecting) {// Entry.target can get that dom element const img = entry.target; img.src = img.dataset.src; Imageobserve. unobserve(img); }}); }); [...imgs]. ForEach ((img) => {// enable monitoring each element imageobserve.observe.img; }); }else {
          alert("Your browser does not support IntersectionObserver!"); }});Copy the code
  • The effect

All the code

3. Summary

There are three ways to implement lazy loading. I personally prefer the third implementation because it helps us to automatically listen and then unlisten after loading so that we don’t have to do throttling optimization ourselves. However, this approach requires consideration of browser compatibility.