react lazyload实现
实现 React 懒加载的几种方法
使用 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>
);
}
图片懒加载
通过 Intersection Observer API 或第三方库(如 react-lazyload)实现图片懒加载。
方法1:使用 Intersection Observer
import { useEffect, useRef } from 'react';
function 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} />;
}
方法2:使用 react-lazyload 库
import LazyLoad from 'react-lazyload';
function App() {
return (
<LazyLoad height={200} offset={100}>
<img src="image.jpg" alt="Lazy-loaded" />
</LazyLoad>
);
}
路由懒加载
结合 React.lazy 和 React Router 实现路由级懒加载。
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense } from 'react';
const Home = React.lazy(() => import('./routes/Home'));
const About = React.lazy(() => import('./routes/About'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Suspense>
</Router>
);
}
注意事项
React.lazy仅支持默认导出(export default)。Suspense的fallback需提供加载状态提示。- 图片懒加载需考虑兼容性,
Intersection Observer可能需要 polyfill。 - 生产环境中建议预加载关键资源,避免性能问题。






