返回 AiToEarn
rendering-resource-hints.md
根目录 / project / aitoearn-web / .agents / skills / vercel-react-best-practices / rules / rendering-resource-hints.md
1 ---
2 title: Use React DOM Resource Hints
3 impact: HIGH
4 impactDescription: reduces load time for critical resources
5 tags: rendering, preload, preconnect, prefetch, resource-hints
6 ---
7
8 ## Use React DOM Resource Hints
9
10 **Impact: HIGH (reduces load time for critical resources)**
11
12 React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
13
14 - **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
15 - **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
16 - **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
17 - **`preloadModule(href)`**: Fetch an ES module you'll use soon
18 - **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
19 - **`preinitModule(href)`**: Fetch and evaluate an ES module
20
21 **Example (preconnect to third-party APIs):**
22
23 ```tsx
24 import { preconnect, prefetchDNS } from 'react-dom'
25
26 export default function App() {
27 prefetchDNS('https://analytics.example.com')
28 preconnect('https://api.example.com')
29
30 return <main>{/* content */}</main>
31 }
32 ```
33
34 **Example (preload critical fonts and styles):**
35
36 ```tsx
37 import { preload, preinit } from 'react-dom'
38
39 export default function RootLayout({ children }) {
40 // Preload font file
41 preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
42
43 // Fetch and apply critical stylesheet immediately
44 preinit('/styles/critical.css', { as: 'style' })
45
46 return (
47 <html>
48 <body>{children}</body>
49 </html>
50 )
51 }
52 ```
53
54 **Example (preload modules for code-split routes):**
55
56 ```tsx
57 import { preloadModule, preinitModule } from 'react-dom'
58
59 function Navigation() {
60 const preloadDashboard = () => {
61 preloadModule('/dashboard.js', { as: 'script' })
62 }
63
64 return (
65 <nav>
66 <a href="/dashboard" onMouseEnter={preloadDashboard}>
67 Dashboard
68 </a>
69 </nav>
70 )
71 }
72 ```
73
74 **When to use each:**
75
76 | API | Use case |
77 |-----|----------|
78 | `prefetchDNS` | Third-party domains you'll connect to later |
79 | `preconnect` | APIs or CDNs you'll fetch from immediately |
80 | `preload` | Critical resources needed for current page |
81 | `preloadModule` | JS modules for likely next navigation |
82 | `preinit` | Stylesheets/scripts that must execute early |
83 | `preinitModule` | ES modules that must execute early |
84
85 Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
86
86 lines MARKDOWN