React中如何实现延迟加载
使用React.lazy和Suspense实现组件级延迟加载
React.lazy函数允许动态导入组件,结合Suspense组件实现加载时的降级处理。这种方式适用于路由级或大型组件的按需加载。
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
动态导入配合状态管理
对于更细粒度的控制,可以使用动态import()语法配合组件状态管理。这种方法适用于需要条件触发加载的场景。
function LazyLoader() {
const [Component, setComponent] = useState(null);
useEffect(() => {
import('./HeavyComponent').then(comp => {
setComponent(comp.default);
});
}, []);
return Component ? <Component /> : <LoadingSpinner />;
}
路由级别的代码分割
React Router与React.lazy天然适配,可以实现基于路由的代码分割。这种模式在单页应用中特别有效。

const Home = React.lazy(() => import('./routes/Home'));
const About = React.lazy(() => import('./routes/About'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
);
}
图片资源的懒加载
对于非组件资源如图片,可以使用原生loading="lazy"属性或Intersection Observer API。现代浏览器已原生支持图片懒加载。
<img
src="placeholder.jpg"
data-src="actual-image.jpg"
loading="lazy"
onLoad={e => {
e.target.src = e.target.dataset.src;
}}
/>
第三方库实现高级功能
使用react-lazyload等第三方库可以获得更多高级功能如阈值控制、占位符管理等。这些库通常基于Intersection Observer实现。

import LazyLoad from 'react-lazyload';
<LazyLoad height={200} offset={100}>
<img src="actual-image.jpg" />
</LazyLoad>
Webpack配置优化
配合打包工具如Webpack,可以通过魔术注释控制代码分割行为。这种方式可以优化最终的bundle生成策略。
const Component = React.lazy(() => import(
/* webpackChunkName: "special-chunk" */
/* webpackPrefetch: true */
'./SpecialComponent'
));
服务端渲染兼容方案
在SSR场景下需要使用@loadable/component等专门库。这些解决方案能正确处理服务器端的模块加载。
import loadable from '@loadable/component';
const LazyComponent = loadable(() => import('./LazyComponent'));
function App() {
return <LazyComponent fallback={<div>Loading...</div>} />;
}






