管理后台往往包含图表、富文本编辑器和大型配置面板。如果所有模块都在首屏引入,初始 JavaScript 体积和解析成本会增加。React lazy 与 Suspense 可以将部分组件延迟加载。本文关注客户端代码拆分及加载失败处理,不讨论服务端渲染。
1. 决定哪些模块值得拆分
拆分应围绕用户是否立即需要某项功能。首屏核心按钮不适合延迟;用户点击后才打开的图表配置面板更适合独立加载。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/01c942d8579e23b288f501b962138fff6b7afa56">
<section><h2>分析工作台</h2><button onClick={() => setShowChart(true)}>打开详细图表</button></section>
</div>
2. 在模块顶层声明 lazy 组件
lazy 接收返回模块 Promise 的函数。默认导出必须是 React 组件。不要在普通组件函数内部反复声明 lazy,否则组件身份可能变化并重置状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/031fc2b4ebe9e073ea48634b5b568ae45add3205">
{showChart && <LazyChart reportId={reportId} />}
</div>
import { lazy } from 'react';
const LazyChart = lazy(() => import('./ChartPanel'));
3. 给延迟模块设置局部 Suspense 边界
Suspense 的 fallback 应尽量靠近需要等待的组件。将整个页面放在一个边界中,可能使原本可用的导航也被加载提示替换。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
<section aria-label="图表区">
<Suspense fallback={<p role="status">正在加载图表模块</p>}>
<LazyChart reportId={reportId} />
</Suspense>
</section>
</div>
4. 正确设计加载占位
骨架屏应保留与实际组件相近的布局尺寸,避免模块加载后界面突然跳动。装饰骨架不应该被辅助技术当作大量真实内容朗读。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/690f209d77c4b377f85c70fd81fbe6842ab0b57f">
<section aria-busy="true" aria-label="加载图表">
<div className="chart-skeleton" aria-hidden="true" />
<span role="status">图表加载中</span>
</section>
</div>
.chart-skeleton {
min-block-size: 18rem; background: #eef2f7; border-radius: .5rem; }
5. 模块加载失败需要错误边界
Suspense 负责等待,不负责渲染错误后的恢复。动态 import 拒绝时应由 Error Boundary 捕获,提供可理解的错误信息。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/397f2296144ec139ad909ed6073bc56fc3d4e558">
<ModuleErrorBoundary>
<Suspense fallback={<p>加载配置模块</p>}><LazyChart reportId={reportId} /></Suspense>
</ModuleErrorBoundary>
</div>
class ModuleErrorBoundary extends React.Component<React.PropsWithChildren, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
render() {
return this.state.failed ? <p role="alert">模块加载失败,请刷新页面后重试</p> : this.props.children;
}
}
6. 不要假设重置边界就能重新下载模块
React lazy 会缓存加载 Promise 及其结果。若动态 import 已失败,仅切换组件 key 不保证重新发起网络请求。应根据部署策略提供重新加载页面或明确模块重试机制。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d3fbbd526808b9378d86a88f1199eafe7e855613">
<section role="alert"><p>当前模块暂不可用</p><button onClick={() => location.reload()}>重新加载页面</button></section>
</div>
7. 适当预加载高概率使用的模块
当用户将鼠标移到展开按钮或键盘焦点进入时,可提前加载模块以缩短等待。但不要无条件预取所有功能。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/115366d0e61d87541a12f1b18745079ac292f282">
<button onPointerEnter={preloadChart} onFocus={preloadChart} onClick={() => setShowChart(true)}>查看图表</button>
</div>
const loadChart = () => import('./ChartPanel');
const LazyChart = lazy(loadChart);
function preloadChart() {
void loadChart().catch(() => {
}); }
8. 使用独立边界保持其他交互
图表和报表编辑器可能相互独立,应该分别等待。多个边界可以让用户在一个区域加载时继续操作另一个区域。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a2f13ad1991e0f598de03b9a82da17f67f901b33">
<section>
<Suspense fallback={<p>加载图表</p>}><LazyChart reportId={reportId} /></Suspense>
<Suspense fallback={<p>加载编辑器</p>}><LazyEditor /></Suspense>
</section>
</div>
Suspense 不会自动把 useEffect 中的 fetch 转换为可挂起数据源。普通异步请求依旧需要明确的加载状态,或使用支持 Suspense 的数据层。
9. 切换已显示内容时保持响应
如果状态切换可能导致已显示区域重新挂起,可以考虑 transition,让 React 区分紧急输入和非紧急视图更新。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/51652c9f07b7eaaab956f778f3008867ee1fe5ac">
<button onClick={() => startTransition(() => setReportId(nextReportId))}>切换报表</button>
{isPending && <span role="status">正在切换</span>}
</div>
const [isPending, startTransition] = useTransition();
10. 用构建结果和网络面板验证收益
仅使用 lazy 不代表拆包一定有效。检查生成的 chunk、请求时机、共享依赖和慢网下体验,避免把大模块的全部成本转移到首次点击。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/5de111f3a6f0157e24507ff84a74e361871d8be2">
<ul aria-label="验收项"><li>首次访问不下载非必要模块</li><li>打开功能时显示等待状态</li><li>加载失败有恢复提示</li></ul>
</div>
应在生产构建下进行验证,并覆盖旧页面引用新部署后已失效 chunk 的情况。保留合理的版本切换及资源缓存策略。
总结
lazy 负责组件模块的延迟加载,Suspense 负责等待期间的呈现,错误边界负责失败后的反馈。把三者与实际访问概率和构建结果结合,才能真正改善前端交互性能。