react如何延迟加载
延迟加载的实现方法
在React中实现延迟加载(Lazy Loading)通常指按需加载组件或资源,以提升初始页面加载性能。以下是几种常见方法:
使用React.lazy和Suspense
React.lazy配合Suspense是官方推荐的组件级延迟加载方案:

import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
React.lazy接收一个返回动态import的函数Suspense提供加载中的备用UI- 适用于路由级或大型组件的代码分割
路由级代码分割
配合React Router实现路由级别的延迟加载:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const Home = React.lazy(() => import('./routes/Home'));
const About = React.lazy(() => import('./routes/About'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</Router>
);
}
图片延迟加载
对于媒体资源的延迟加载,可使用原生loading属性或Intersection Observer:
// 原生方式
<img src="image.jpg" loading="lazy" alt="示例" />
// 观察者API实现
const LazyImage = ({ src, alt }) => {
const imgRef = useRef();
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
imgRef.current.src = src;
observer.unobserve(imgRef.current);
}
});
observer.observe(imgRef.current);
return () => observer.disconnect();
}, [src]);
return <img ref={imgRef} alt={alt} />;
};
动态加载第三方库
非核心库可在使用时动态加载:
function loadLibrary() {
return import('heavy-library').then(module => module.default);
}
function Component() {
const handleClick = async () => {
const library = await loadLibrary();
library.doSomething();
};
return <button onClick={handleClick}>Load</button>;
}
注意事项
- 生产环境需确保打包工具(如Webpack)支持代码分割
- 避免过度分割导致过多小文件请求
- 测试加载状态和错误边界处理
- Next.js等框架有内置的延迟加载方案
这些方法可显著减少初始包大小,提升页面交互准备时间(TTI)。实际应用中应根据具体场景选择合适策略。






