亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

利用IntersectionObserver實現(xiàn)動態(tài)渲染的示例詳解

 更新時間:2022年12月28日 15:24:35   作者:萌魚  
IntersectionObserver誕生已經(jīng)有幾年了,所以它的兼容性目前已經(jīng)達到可以使用的程度了。本文主要介紹了如何利用IntersectionObserver實現(xiàn)動態(tài)渲染,感興趣的可以了解一下

前言

開發(fā)表格時,希望支持可視后的動態(tài)加載。在查找資料做了一些嘗試后,最終使用IntersectionObserver,相對方便地實現(xiàn)了該功能

IntersectionObserver誕生已經(jīng)有幾年了,所以它的兼容性目前已經(jīng)達到可以使用的程度了。具體兼容程度以及詳細API可參考CDN

實現(xiàn)

懶加載組件

核心就是利用了IntersectionObserver的能力,封裝了LazyContainer組件,該組件的children,只有在視口中可見時,才會真正渲染

export const LazyContainer = (props) => {
  const { children } = props;
  const $ref = useRef<HTMLDivElement>(null);
  const [isReady, setReady] = useState(false);
  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      // 一個observer可以監(jiān)聽多個元素,本例中只有一個
      entries.forEach((entry) => {
        // isIntersecting:目標元素與觀察者元素(一般為視口)是否相交
        if (!isReady && entry.isIntersecting) {
          setReady(true);
          // 首次加載完后,便停止監(jiān)聽
          observer.disconnect();
        }
      });
    });
    observer.observe($ref.current as Element);
  }, []);
  return <div ref={$ref}>{isReady ? children : null}</div>;
};

長列表組件示意

簡潔實現(xiàn)一個長列表,測試LazyContainer組件

export const LongList = (props) => {
  const { loop = 1, children } = props;
  return (
    <ul>
      {Array.from({ length: loop }).map((x, i) => {
        return (
          <li style={{ height: '200px', marginBottom: '20px' }}>
            {React.cloneElement(children, { key: i, num: i })}
          </li>
        );
      })}
    </ul>
  );
};

測試

在頁面上測試一下該功能

<LongList loop={3}>
  <LazyContainer num={1}>
    {/* 利用img加載做一個測試 */}
    <img src="圖片地址"></img>
  </LazyContainer>
</LongList>

在chrome network中開啟slow 3G,然后讓LongList中的元素一個接一個出現(xiàn),就可以明顯看到圖片是一個接一個進行加載的。

到此這篇關于利用IntersectionObserver實現(xiàn)動態(tài)渲染的示例詳解的文章就介紹到這了,更多相關IntersectionObserver動態(tài)渲染內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論