fb79a15508
- 添加 sections 定义文件,包含性能优化各领域分类 - 添加规则模板文件,规范文档结构和标签定义 - 添加异步操作优化规则,包括防止瀑布流、并行化、延迟等待等 - 添加包大小优化规则,包括避免桶式导入、动态导入、预加载等 - 添加服务端性能优化规则,包括 API 路
32 lines
949 B
Markdown
32 lines
949 B
Markdown
---
|
|
title: Conditional Module Loading
|
|
impact: HIGH
|
|
impactDescription: loads large data only when needed
|
|
tags: bundle, conditional-loading, lazy-loading
|
|
---
|
|
|
|
## Conditional Module Loading
|
|
|
|
Load large data or modules only when a feature is activated.
|
|
|
|
**Example (lazy-load animation frames):**
|
|
|
|
```tsx
|
|
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
|
|
const [frames, setFrames] = useState<Frame[] | null>(null)
|
|
|
|
useEffect(() => {
|
|
if (enabled && !frames && typeof window !== 'undefined') {
|
|
import('./animation-frames.js')
|
|
.then(mod => setFrames(mod.frames))
|
|
.catch(() => setEnabled(false))
|
|
}
|
|
}, [enabled, frames, setEnabled])
|
|
|
|
if (!frames) return <Skeleton />
|
|
return <Canvas frames={frames} />
|
|
}
|
|
```
|
|
|
|
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|