返回 AiToEarn
bundle-preload.md
1 ---
2 title: Preload Based on User Intent
3 impact: MEDIUM
4 impactDescription: reduces perceived latency
5 tags: bundle, preload, user-intent, hover
6 ---
7
8 ## Preload Based on User Intent
9
10 Preload heavy bundles before they're needed to reduce perceived latency.
11
12 **Example (preload on hover/focus):**
13
14 ```tsx
15 function EditorButton({ onClick }: { onClick: () => void }) {
16 const preload = () => {
17 if (typeof window !== 'undefined') {
18 void import('./monaco-editor')
19 }
20 }
21
22 return (
23 <button
24 onMouseEnter={preload}
25 onFocus={preload}
26 onClick={onClick}
27 >
28 Open Editor
29 </button>
30 )
31 }
32 ```
33
34 **Example (preload when feature flag is enabled):**
35
36 ```tsx
37 function FlagsProvider({ children, flags }: Props) {
38 useEffect(() => {
39 if (flags.editorEnabled && typeof window !== 'undefined') {
40 void import('./monaco-editor').then(mod => mod.init())
41 }
42 }, [flags.editorEnabled])
43
44 return <FlagsContext.Provider value={flags}>
45 {children}
46 </FlagsContext.Provider>
47 }
48 ```
49
50 The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
51
51 lines MARKDOWN