react中基于IntersectionObserver给图片加载做优化(图片懒加载)

4 阅读1分钟

用现在比较流行的方式做图片懒加载,在可视化区域进行加载图片.

一个工具函数

// 图片懒加载
export default function lazyLoadImg(targetEle: HTMLElement) {
  const elements = targetEle.querySelectorAll('img[data-src]');
  const observer = new IntersectionObserver((entries) => {
    for (const entry of entries) {
      if (entry.isIntersecting) {
        const img = entry.target
        img.src = img.dataset.src
        observer.unobserve(img)
      }
    }
  }, {
    // rootMargin: '10px',
    threshold: 0 // 
  });
  elements.forEach((dom) => {
    observer.observe(dom);//每个元素,添加聆听事件
  });
}

react中调用

import React, {memo, useState, useEffect,useRef } from 'react';

// 图片懒加载
  const loadingImgRef = useRef(null);
  useEffect(() => {
    if(cardList.length > 0) {
      console.log('cardList', cardList)
      const targetEle = loadingImgRef.current;
      lazyLoadImg(targetEle)
    }
  }, [cardList]);


render函数

<div ref={loadingImgRef}>
     <img className={styles.checkImg} src='' data-src={card.img} alt="" />
<div>