react实现lazyload
React 实现 LazyLoad
使用 React.lazy 和 Suspense 实现组件懒加载React.lazy 是 React 官方提供的懒加载组件的方法,结合 Suspense 可以优雅地处理加载状态。
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
fallback 用于在组件加载时显示占位内容。
图片懒加载(Intersection Observer API)
通过 Intersection Observer 监听图片是否进入视口,动态加载资源。

import React, { useEffect, useRef } from 'react';
const LazyImage = ({ src, alt }) => {
const imgRef = useRef();
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = src;
observer.unobserve(img);
}
});
});
observer.observe(imgRef.current);
return () => observer.disconnect();
}, [src]);
return <img ref={imgRef} alt={alt} />;
};
// 使用示例
<LazyImage src="image-url.jpg" alt="Lazy-loaded image" />
第三方库实现(react-lazyload)react-lazyload 是一个流行的懒加载库,支持组件和图片的懒加载。
安装:
npm install react-lazyload
使用示例:

import LazyLoad from 'react-lazyload';
function App() {
return (
<LazyLoad height={200} offset={100}>
<img src="image.jpg" alt="Lazy-loaded" />
</LazyLoad>
);
}
offset 控制提前加载的像素范围,height 设置占位高度。
路由懒加载(React Router)
结合 React.lazy 实现路由级别的懒加载:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense } from 'react';
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Suspense>
</Router>
);
}
注意事项
- 懒加载的组件必须导出为
default。 - 生产环境下需确保打包工具(如 Webpack)支持代码分割。
- 图片懒加载时,建议使用占位图或骨架屏优化用户体验。






