docs(vercel-react-best-practices): 添加 Vercel React 最佳实践规则文档
- 添加 sections 定义文件,包含性能优化各领域分类 - 添加规则模板文件,规范文档结构和标签定义 - 添加异步操作优化规则,包括防止瀑布流、并行化、延迟等待等 - 添加包大小优化规则,包括避免桶式导入、动态导入、预加载等 - 添加服务端性能优化规则,包括 API 路
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
---
|
||||
title: Use defer or async on Script Tags
|
||||
impact: HIGH
|
||||
impactDescription: eliminates render-blocking
|
||||
tags: rendering, script, defer, async, performance
|
||||
---
|
||||
|
||||
## Use defer or async on Script Tags
|
||||
|
||||
**Impact: HIGH (eliminates render-blocking)**
|
||||
|
||||
Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
|
||||
|
||||
- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
|
||||
- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
|
||||
|
||||
Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
|
||||
|
||||
**Incorrect (blocks rendering):**
|
||||
|
||||
```tsx
|
||||
export default function Document() {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<script src="https://example.com/analytics.js" />
|
||||
<script src="/scripts/utils.js" />
|
||||
</head>
|
||||
<body>{/* content */}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking):**
|
||||
|
||||
```tsx
|
||||
export default function Document() {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
{/* Independent script - use async */}
|
||||
<script src="https://example.com/analytics.js" async />
|
||||
{/* DOM-dependent script - use defer */}
|
||||
<script src="/scripts/utils.js" defer />
|
||||
</head>
|
||||
<body>{/* content */}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
|
||||
|
||||
```tsx
|
||||
import Script from 'next/script'
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<>
|
||||
<Script src="https://example.com/analytics.js" strategy="afterInteractive" />
|
||||
<Script src="/scripts/utils.js" strategy="beforeInteractive" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
|
||||
Reference in New Issue
Block a user