使用 Intersection Observer API 实现懒加载 - LogRocket 博客

作者:API传播员 · 2025-11-23 · 阅读时间:6分钟

延迟加载是一种优化技术,它允许我们将应用程序中非必要内容的加载延迟到初始页面加载完成之后。通过优先加载最基本的内容,并在用户需要时动态加载剩余内容,可以有效减小应用程序的捆绑包大小,从而提高页面初次加载的速度。

在现代应用中,延迟加载的实现方式多种多样,其中最常见的一种是无限滚动。页面内容会随着用户向下滚动逐步加载。此外,还可以通过代码拆分技术进一步优化延迟加载,尤其是在 React 应用中,通过将代码拆分为可延迟加载的模块,显著减少初始捆绑包的大小。


使用 Intersection Observer API 实现懒加载

随着 Web 技术的不断发展,浏览器支持的功能和 API 也在不断更新。过去,开发者在实现基于 DOM 元素可见性功能时,常常需要依赖 JavaScript 或 jQuery 等库,这不仅复杂且容易导致代码混乱。而现代浏览器通过引入新的 API,如 Intersection Observer API,大大简化了这一过程。

什么是 Intersection Observer API?

Intersection Observer API 提供了一种高效的方式来观察特定元素与视口或祖先元素的交集变化。通过该 API,开发者可以轻松检测元素的可见性,而无需编写复杂的代码逻辑。

Intersection Observer API 的常见用途

  • 滚动页面时延迟加载图像或其他内容
  • 实现无限滚动功能
  • 检测广告元素的可见性以计算广告收入
  • 在元素可见时触发特定代码逻辑

以下是使用 Intersection Observer API 创建观察器的基本代码:

let observer = new IntersectionObserver(callback, options);
  • callback:当目标元素与视口或指定祖先元素相交时触发的回调函数。
  • options:一个配置对象,用于控制观察行为。

配置对象 options 的字段

  • root:指定用于检测目标元素可见性的祖先元素,默认为视口。
  • rootMargin:定义根元素周围的边距,可接受 CSS 值(如像素或百分比)。
  • threshold:触发回调的阈值,表示目标元素可见部分的比例。

以下是一个完整的示例代码:

const options = {
  root: document.querySelector(".container"),
  rootMargin: "10px",
  threshold: 0.5,
};

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => console.log("element", entry));
}, options);const target = document.querySelector(".header");
observer.observe(target);

使用 Intersection Observer API 的注意事项

  • 当目标元素达到指定阈值时,回调函数会接收到一个 IntersectionObserverEntry 对象列表。
  • 如果未设置 root,则默认使用浏览器视口。
  • 目标元素必须是根元素的子元素。
  • 如果需要观察多个元素,需要逐一调用 observe 方法。

实际应用场景:在 React 中使用 Intersection Observer API

接下来,我们将通过一个 React 示例展示如何使用 Intersection Observer API。

创建 React 项目

使用以下命令创建一个新的 React 项目:

npx create-react-app intersection-observer-in-practice

添加样式

在默认的 styles.css 文件中,添加以下样式代码:

.root {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.section {
  height: 100vh;
  width: 100%;
}.target {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #151419;
  color: #fff;
  font-weight: 900;
  font-size: 20px;
  width: 300px;
  height: 200px;
  border-radius: 5px;
}.isVisible {
  position: fixed;
  top: 0;
  width: 100%;
  background: #151419;
  color: #fff;
  font-size: 20px;
  font-weight: 900;
  padding: 40px;
}

实现 Intersection Observer API

在 React 组件中,我们将创建一个简单的示例,当目标元素可见时,更新页面内容。

创建状态和引用

const rootRef = useRef(null);
const [isVisible, setIsVisible] = useState(false);

配置观察器选项

const options = {
  root: null,
  rootMargin: "0px",
  threshold: 1.0,
};

创建观察器

useEffect(() => {
  const observer = new IntersectionObserver((entries) => {
    const [entry] = entries;
    setIsVisible(entry.isIntersecting);
  }, options);

  if (rootRef.current) observer.observe(rootRef.current);  return () => {
    if (rootRef.current) observer.unobserve(rootRef.current);
  };
}, [rootRef, options]);

完整代码示例

export default App;

const App = () => {
const rootRef = useRef(null);
const [isVisible, setIsVisible] = useState(false);

useEffect(() => {
const options = {
root: null,
rootMargin: "0px",
threshold: 1.0,
};

const observer = new IntersectionObserver((entries) => {
const [entry] = entries;
setIsVisible(entry.isIntersecting);
}, options);

if (rootRef.current) observer.observe(rootRef.current);

return () => {
if (rootRef.current) observer.unobserve(rootRef.current);
};
}, []);

return (
<div>
<div>Scroll down</div>
<div>
Target Element
</div>
</div>
);
};

export default App;

使用第三方库:react-intersection-observer

如果希望简化开发,可以使用 react-intersection-observer 库。以下是使用该库的示例:

import React from "react";
import { useInView } from "react-intersection-observer";

const Component = () => {
  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 1.0,
  };  const { ref, inView } = useInView(options);  return (
    <div>
      <h2>{Header inside viewport: ${inView}}</h2>
    </div>
  );
};export default Component;

结论

Intersection Observer API 是一个强大的工具,可以帮助开发者轻松实现延迟加载、无限滚动等功能。通过减少加载时间和优化用户体验,该 API 为现代 Web 应用提供了无限可能性。无论是使用原生 API 还是第三方库,都可以快速实现高效的懒加载功能。

原文链接: https://blog.logrocket.com/lazy-loading-using-the-intersection-observer-api/