frontend-fullchain-optimization
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFrontend Full-Chain Performance Optimization Guide
前端全链路性能优化指南
A frontend performance diagnostic and optimization system based on Web Vitals core metrics. Core principle: User-centric — optimization is about doing less, not more.
基于Web Vitals核心指标构建的前端性能诊断与优化体系。核心原则:以用户为中心——优化的核心是做减法,而非加法。
Metric Threshold Quick Reference
指标阈值速查
| Metric | Good | Needs Improvement | Poor | Unit | Focus |
|---|---|---|---|---|---|
| LCP | ≤ 2.5s | 2.5s - 4s | > 4s | Time | Largest Contentful Paint |
| FCP | ≤ 1.8s | 1.8s - 3s | > 3s | Time | First Contentful Paint |
| INP | ≤ 200ms | 200ms - 500ms | > 500ms | Time | Interaction to Next Paint |
| CLS | ≤ 0.1 | 0.1 - 0.25 | > 0.25 | Score | Visual Stability |
| TTFB | ≤ 800ms | 800ms - 1.8s | > 1.8s | Time | Time to First Byte |
| FID | ≤ 100ms | 100ms - 300ms | > 300ms | Time | First Input Delay |
| TBT | Tasks > 50ms are long tasks | — | — | Time | Total Blocking Time |
Measurement advice: Don't rely on a single P75. Combine P60/P75/P90/P99 percentiles with daily avg/max/min trend lines. Desktop: target P98+; Mobile core pages: target P95–P99.
| 指标 | 优秀 | 需要改进 | 较差 | 单位 | 关注重点 |
|---|---|---|---|---|---|
| LCP | ≤ 2.5s | 2.5s - 4s | > 4s | 时间 | 最大内容绘制(Largest Contentful Paint) |
| FCP | ≤ 1.8s | 1.8s - 3s | > 3s | 时间 | 首次内容绘制(First Contentful Paint) |
| INP | ≤ 200ms | 200ms - 500ms | > 500ms | 时间 | 交互到下一次绘制(Interaction to Next Paint) |
| CLS | ≤ 0.1 | 0.1 - 0.25 | > 0.25 | 分数 | 视觉稳定性(Visual Stability) |
| TTFB | ≤ 800ms | 800ms - 1.8s | > 1.8s | 时间 | 首字节时间(Time to First Byte) |
| FID | ≤ 100ms | 100ms - 300ms | > 300ms | 时间 | 首次输入延迟(First Input Delay) |
| TBT | 任务时长>50ms即为长任务 | — | — | 时间 | 总阻塞时间(Total Blocking Time) |
测量建议:不要仅依赖单一P75值。结合P60/P75/P90/P99分位数与日均/最高/最低趋势线。桌面端:目标P98+;移动端核心页面:目标P95–P99。
Diagnostic Decision Tree
诊断决策树
text
Page loads slowly?
├── TTFB > 800ms → Network/server issue → See "TTFB Optimization"
├── FCP > 1.8s → Resource blocking/large files → See "FCP Optimization"
├── LCP > 2.5s
│ ├── TTFB & FCP normal → Slow viewport resource loading → See "LCP Optimization"
│ └── TTFB or FCP abnormal → Fix upstream metrics first
├── INP > 200ms → Long tasks blocking main thread → See "INP Optimization"
├── CLS > 0.1 → Layout shifts → See "CLS Optimization"
└── Lighthouse Performance Score
├── > 80: Few issues
├── 60-80: Needs focused analysis, priority: FCP → LCP → CLS
└── < 60: Severe issues, full audit requiredtext
页面加载缓慢?
├── TTFB > 800ms → 网络/服务器问题 → 查看「TTFB优化」
├── FCP > 1.8s → 资源阻塞/文件过大 → 查看「FCP优化」
├── LCP > 2.5s
│ ├── TTFB & FCP正常 → 视口资源加载缓慢 → 查看「LCP优化」
│ └── TTFB或FCP异常 → 先修复上游指标
├── INP > 200ms → 长任务阻塞主线程 → 查看「INP优化」
├── CLS > 0.1 → 布局偏移 → 查看「CLS优化」
└── Lighthouse性能评分
├── > 80: 问题较少
├── 60-80: 需要针对性分析,优先级:FCP → LCP → CLS
└── < 60: 问题严重,需全面审计INP Optimization (Interaction Responsiveness)
INP优化(交互响应性)
Diagnosis: Chrome Performance panel — look for long tasks (> 50ms, highlighted red); inspect event handler duration in the flame chart.
Strategy — Break long tasks into shorter ones:
| Method | Mechanism | Use Case |
|---|---|---|
| Creates a new macrotask at the end of the queue | Non-urgent network requests, DB operations |
| Creates a microtask, runs immediately after current macrotask | Secondary tasks needing faster execution |
| Runs before next repaint | Rendering-related tasks |
| Lowest priority, runs when main thread is idle | Analytics, logging |
| Fine-grained priority control | Scenarios requiring precise scheduling |
postTask priorities: (high) > (medium) > (low)
user-blockinguser-visiblebackgroundLayout & Rendering Optimization:
- Reduce usage frequency; avoid unnecessary pseudo-class selectors (
calc(),nth-child,nth-last-child)not() - Avoid frequent JS modifications to element position/size; use className or cssText for batch updates
- Avoid alternating DOM read/write in loops (layout thrashing): cache reads into variables first, then batch write
- Use skeleton screens for lazy-loaded content
- Use (Fragment) instead of meaningless
<></>wrappers<div> - DOM nodes > 800: caution; > 1400: excessive
- Use virtualization for long lists (react-window / vue-virtual-scroll-list)
- Swiper lists: preload only current item ± 1
CSS Optimization:
- Avoid layout; reduce deeply nested CSS selectors
table - Use GPU-accelerated animations: /
transformtrigger compositing layer; avoidopacity/topwhich trigger reflowleft - Use semantic HTML elements; avoid meaningless tags (e.g., use not
<button>for buttons)<div>
诊断方法:Chrome性能面板——查找长任务(>50ms,红色高亮);在火焰图中检查事件处理程序的耗时。
策略——将长任务拆分为短任务:
| 方法 | 机制 | 使用场景 |
|---|---|---|
| 在队列末尾创建新的宏任务 | 非紧急网络请求、数据库操作 |
| 创建微任务,在当前宏任务完成后立即执行 | 需要更快执行的次要任务 |
| 在下一次重绘前执行 | 渲染相关任务 |
| 最低优先级,主线程空闲时执行 | 埋点统计、日志记录 |
| 细粒度优先级控制 | 需要精确调度的场景 |
postTask优先级:(高)> (中)> (低)
user-blockinguser-visiblebackground布局与渲染优化:
- 减少的使用频率;避免不必要的伪类选择器(
calc()、nth-child、nth-last-child)not() - 避免通过JS频繁修改元素位置/尺寸;使用className或cssText进行批量更新
- 避免在循环中交替进行DOM读写(布局抖动):先将读取结果缓存到变量中,再批量写入
- 懒加载内容使用骨架屏
- 使用(Fragment)替代无意义的
<></>包裹层<div> - DOM节点数量>800需注意;>1400则过多
- 长列表使用虚拟化(react-window / vue-virtual-scroll-list)
- Swiper列表:仅预加载当前项±1个
CSS优化:
- 避免布局;减少深度嵌套的CSS选择器
table - 使用GPU加速动画:/
transform触发合成层;避免使用opacity/top(会触发重排)left - 使用语义化HTML元素;避免无意义标签(例如按钮使用而非
<button>)<div>
TTFB Optimization (Network & Server)
TTFB优化(网络与服务器)
Diagnostic formula:
TTFB ≈ HTTP request time + Server processing time + HTTP response timeDiagnosis: DevTools Network panel → click request → Timing → "Waiting for server response" = TTFB.
TTFB differences by page type: Static pages (CDN direct, fastest) < SPA (tiny HTML shell, near-static) < SSR (Node.js computation required, slowest). Adjust baseline by page type.
| Direction | Strategy |
|---|---|
| General | CDN acceleration (solves 90%+; proactively purge CDN cache after deploys), HTTP/2 multiplexing, Gzip compression, code splitting & dynamic imports |
| UX | Web Workers for heavy requests, DNS prefetch |
| Server (SSR) | Internal network for APIs, Redis cache for low-frequency data, reduce redirects, pre-generate static pages at build time |
| Resource Caching | App hot-update: pre-download HTML/JS/CSS locally (TTFB ≈ 0), PWA Service Worker offline cache |
诊断公式:
TTFB ≈ HTTP请求时间 + 服务器处理时间 + HTTP响应时间诊断方法:DevTools网络面板→点击请求→Timing→「Waiting for server response」即为TTFB。
不同页面类型的TTFB差异:静态页面(CDN直连,最快)< SPA(极小HTML壳,接近静态)< SSR(需Node.js计算,最慢)。需根据页面类型调整基准线。
| 优化方向 | 策略 |
|---|---|
| 通用 | CDN加速(解决90%+问题;部署后主动清理CDN缓存)、HTTP/2多路复用、Gzip压缩、代码分割与动态导入 |
| 用户体验 | 复杂请求使用Web Workers、DNS预取 |
| 服务器(SSR) | API使用内网调用、低频数据用Redis缓存、减少重定向、构建时预生成静态页面 |
| 资源缓存 | 应用热更新:本地预下载HTML/JS/CSS(TTFB≈0)、PWA Service Worker离线缓存 |
FCP Optimization (White Screen & First Content)
FCP优化(白屏与首次内容)
Diagnostic formula:
FCP ≈ TTFB + Resource download time + DOM parse time + Render timeWhite screen time ≈ FCP time. Target: instant open (< 1s).
| Strategy | Details |
|---|---|
| Remove render-blocking resources | Add |
| Reduce JS/CSS size | Remove unused code, Tree Shaking, code splitting |
| Control network payload | Compress above-fold images, use WebP/AVIF, lazy-load videos with placeholders |
| Caching strategy | |
| Shorten critical request depth | Reduce nested resource dependencies (e.g., CSS @import chains); flatten critical resource request chains |
| Font optimization | See "Font Optimization Strategies" below |
| White screen solutions | PWA (international markets); App hot-update local loading (domestic markets) |
诊断公式:
FCP ≈ TTFB + 资源下载时间 + DOM解析时间 + 渲染时间白屏时间≈FCP时间。目标:秒开(<1s)。
| 策略 | 细节 |
|---|---|
| 移除渲染阻塞资源 | 为script标签添加 |
| 缩小JS/CSS体积 | 移除未使用代码、Tree Shaking、代码分割 |
| 控制网络负载 | 压缩首屏图片、使用WebP/AVIF格式、视频懒加载并添加占位符 |
| 缓存策略 | |
| 缩短关键请求链 | 减少嵌套资源依赖(例如CSS @import链);扁平化关键资源请求链 |
| 字体优化 | 查看下方「字体优化策略」 |
| 白屏解决方案 | 海外市场用PWA;国内市场用应用热更新本地加载 |
Font Optimization Strategies
字体优化策略
| Approach | Description |
|---|---|
| Limit font count | Use only one custom font + system font fallback; don't use different Web Fonts for body and p |
| Prefer WOFF2 | 30% better compression than WOFF, supported by all modern browsers |
| Define character ranges (e.g., CJK U+4E00-9FA5); browser downloads only needed subsets |
| For apps with bundled fonts: |
| |
| CSS Font Loading API | |
| Slow network fallback | Use |
| 方案 | 说明 |
|---|---|
| 限制字体数量 | 仅使用一种自定义字体+系统字体兜底;正文和段落不要使用不同的Web Fonts |
| 优先使用WOFF2 | 比WOFF压缩率高30%,所有现代浏览器均支持 |
| 定义字符范围(例如中日韩U+4E00-9FA5);浏览器仅下载所需子集 |
| 内置字体的应用: |
| |
| CSS Font Loading API | |
| 慢网络兜底 | 使用 |
LCP Optimization (Largest Contentful Paint)
LCP优化(最大内容绘制)
Diagnosis: Performance panel — find the LCP marker element; Lighthouse report "Largest Contentful Paint element" entry.
4 element types LCP can mark:
- elements (most common) and
<img>within SVG<image> <video>attribute image or first frameposter- Elements with CSS background images
url() - Block-level elements containing text nodes
Key insights:
- LCP time is always ≥ FCP time
- If TTFB and FCP are normal but LCP is abnormal → problem is viewport resource loading
- SPA: FCP matters more than LCP; SSR/MPA: LCP matters more than FCP
| Strategy | Details |
|---|---|
| Preload LCP image | |
| Framework image components | Use |
| Split large images | Slice large background images into smaller pieces |
| Image format | PNG/JPEG → WebP/AVIF, saves 30%+ size |
| Cloud image params | Dynamically set image size/quality/format per device (e.g., Alibaba Cloud OSS params) |
| Rich text images | Extract image URLs from content, set |
| Avoid duplicate preloads | When using framework image components (e.g., |
Sampling advice: PV < 1M → full LCP collection; above that → ratio sampling or threshold-based reporting.
诊断方法:性能面板——找到LCP标记元素;Lighthouse报告中的「Largest Contentful Paint element」条目。
LCP可标记的4类元素:
- 元素(最常见)及SVG内的
<img><image> - 的
<video>属性图片或第一帧poster - 带有CSS 背景图的元素
url() - 包含文本节点的块级元素
关键结论:
- LCP时间始终≥FCP时间
- 若TTFB和FCP正常但LCP异常→问题出在视口资源加载
- SPA:FCP比LCP更重要;SSR/MPA:LCP比FCP更重要
| 策略 | 细节 |
|---|---|
| 预加载LCP图片 | |
| 框架图片组件 | 使用 |
| 拆分大图 | 将大型背景图切割为小块 |
| 图片格式 | PNG/JPEG→WebP/AVIF,体积减少30%+ |
| 云图片参数 | 根据设备动态设置图片尺寸/质量/格式(例如阿里云OSS参数) |
| 富文本图片 | 从内容中提取图片URL,提前设置 |
| 避免重复预加载 | 使用带 |
采样建议:PV<1M→全量采集LCP;超过该值→比例采样或基于阈值上报。
CLS Optimization (Layout Shift)
CLS优化(布局偏移)
Diagnostic formula: ,
Layout shift score = Impact fraction × Distance fractionCLS = SUM(all shift scores)Key conclusion: The farther the element shifts + the more viewport area affected → higher CLS.
| Scenario | Optimization Strategy |
|---|---|
| Images | Set |
| Dynamic content | Reserve fixed-size placeholder containers for ads/iframes; avoid inserting content at top of viewport without interaction; inserting near bottom has less CLS impact |
| CSS animations | Use |
| Fonts | |
诊断公式:,
布局偏移分数 = 影响比例 × 距离比例CLS = 所有偏移分数之和核心结论:元素偏移距离越远+影响的视口面积越大→CLS值越高。
| 场景 | 优化策略 |
|---|---|
| 图片 | 为所有 |
| 动态内容 | 为广告/iframe预留固定尺寸的占位容器;避免无交互时在视口顶部插入内容;在底部附近插入对CLS影响更小 |
| CSS动画 | 使用 |
| 字体 | |
General Optimization Tips
通用优化技巧
| Tip | Description |
|---|---|
| Network awareness | |
| SVG icons | All small icons (< 5KB / < 50px) should use SVG instead of images to reduce async requests |
| Responsive degradation | CSS media queries split CSS by screen size; skip background images on small screens |
| Cache-first | Cache list data in LocalStorage; render cache first then async refresh to reduce white screen |
| Request merging | Merge resources, reduce HTTP request count and domain count |
| Rendering mode | Choose SSR (fast first paint) / CSR (strong interactivity) / SSG (static content) by scenario |
| 技巧 | 说明 |
|---|---|
| 网络感知 | |
| SVG图标 | 所有小图标(<5KB / <50px)应使用SVG替代图片,减少异步请求 |
| 响应式降级 | CSS媒体查询按屏幕尺寸拆分CSS;小屏设备跳过背景图 |
| 缓存优先 | 列表数据缓存到LocalStorage;先渲染缓存再异步刷新,减少白屏 |
| 请求合并 | 合并资源,减少HTTP请求数与域名数 |
| 渲染模式选择 | 根据场景选择SSR(首屏快)/CSR(交互强)/SSG(静态内容) |
Practical Examples with External Services
结合外部服务的实践示例
The following examples demonstrate how to implement strategies with CDN, OSS, Redis, and other external services.
以下示例展示如何结合CDN、OSS、Redis等外部服务实现优化策略。
Example 1: Alibaba Cloud OSS — Adaptive Image Quality by Network
示例1:阿里云OSS——按网络自适应图片质量
Use case: Prioritize visible content for slow-network users; reduce image size and download time.
javascript
const BASE_IMAGE_URL =
"https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg";
function getNetworkLevel() {
const connection = navigator.connection || {};
const type = connection.effectiveType || "4g";
// Slow network: slow-2g / 2g / 3g
if (/slow-2g|2g|3g/.test(type)) return "slow";
return "fast";
}
function buildOssImageUrl(baseUrl) {
const level = getNetworkLevel();
// OSS image processing params: lower resolution + quality for slow networks
const ossParams =
level === "slow"
? "x-oss-process=image/resize,w_100/quality,q_60/format,webp"
: "x-oss-process=image/resize,w_300/quality,q_82/format,webp";
return `${baseUrl}?${ossParams}`;
}
function updateHeroImage(imgEl) {
imgEl.src = buildOssImageUrl(BASE_IMAGE_URL);
}
const heroImage = document.querySelector("#hero-image");
if (heroImage) {
updateHeroImage(heroImage);
// Update resource strategy on network change
navigator.connection?.addEventListener("change", () => updateHeroImage(heroImage));
}使用场景:为慢网络用户优先保障可见内容;减少图片体积与下载时间。
javascript
const BASE_IMAGE_URL =
"https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg";
function getNetworkLevel() {
const connection = navigator.connection || {};
const type = connection.effectiveType || "4g";
// 慢网络:slow-2g / 2g / 3g
if (/slow-2g|2g|3g/.test(type)) return "slow";
return "fast";
}
function buildOssImageUrl(baseUrl) {
const level = getNetworkLevel();
// OSS图片处理参数:慢网络降低分辨率+质量
const ossParams =
level === "slow"
? "x-oss-process=image/resize,w_100/quality,q_60/format,webp"
: "x-oss-process=image/resize,w_300/quality,q_82/format,webp";
return `${baseUrl}?${ossParams}`;
}
function updateHeroImage(imgEl) {
imgEl.src = buildOssImageUrl(BASE_IMAGE_URL);
}
const heroImage = document.querySelector("#hero-image");
if (heroImage) {
updateHeroImage(heroImage);
// 网络变化时更新资源策略
navigator.connection?.addEventListener("change", () => updateHeroImage(heroImage));
}Example 2: CDN Proactive Purge (Post-Deploy)
示例2:CDN主动清理缓存(部署后)
Use case: Prevent CDN serving stale resources after SPA deployment, avoiding version inconsistencies.
bash
undefined使用场景:防止SPA部署后CDN提供过期资源,避免版本不一致。
bash
undefinedExecuted by CI/CD or server-side — never expose keys in frontend
由CI/CD或后端执行——切勿在前端暴露密钥
Example: proactively purge entry HTML and critical static assets after deploy
示例:部署后主动清理入口HTML与关键静态资源
curl -X POST "https://your-cdn-provider.example.com/purge"
-H "Authorization: Bearer $CDN_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "urls": [ "https://example.com/index.html", "https://example.com/assets/app.abc123.js", "https://example.com/assets/app.abc123.css" ] }'
-H "Authorization: Bearer $CDN_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "urls": [ "https://example.com/index.html", "https://example.com/assets/app.abc123.js", "https://example.com/assets/app.abc123.css" ] }'
undefinedcurl -X POST "https://your-cdn-provider.example.com/purge"
-H "Authorization: Bearer $CDN_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "urls": [ "https://example.com/index.html", "https://example.com/assets/app.abc123.js", "https://example.com/assets/app.abc123.css" ] }'
-H "Authorization: Bearer $CDN_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "urls": [ "https://example.com/index.html", "https://example.com/assets/app.abc123.js", "https://example.com/assets/app.abc123.css" ] }'
undefinedExample 3: SSR + Redis Cache to Reduce TTFB
示例3:SSR + Redis缓存降低TTFB
Use case: SSR pages reading low-frequency config or first-screen data; reduce DB/remote API latency per request.
javascript
// Node.js (SSR) example
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
export async function getHomepageData() {
const cacheKey = "homepage:data:v1";
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
// Assume this is a slow API or DB query
const data = await fetch("https://api.example.com/homepage").then((r) => r.json());
// Cache for 60s to reduce backend pressure under high concurrency
await redis.set(cacheKey, JSON.stringify(data), "EX", 60);
return data;
}使用场景:SSR页面读取低频配置或首屏数据;减少每次请求的数据库/远程API延迟。
javascript
// Node.js(SSR)示例
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
export async function getHomepageData() {
const cacheKey = "homepage:data:v1";
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
// 假设这是一个慢API或数据库查询
const data = await fetch("https://api.example.com/homepage").then((r) => r.json());
// 缓存60秒,高并发下降低后端压力
await redis.set(cacheKey, JSON.stringify(data), "EX", 60);
return data;
}Tool Usage Recommendations
工具使用建议
| Tool Mode | Use Case |
|---|---|
| Lighthouse Navigation mode | Full process analysis from request to load complete for a single page |
| Lighthouse Timespan mode | INP/CLS analysis for SPA route transitions and form interactions |
| Lighthouse Snapshot mode | Analysis of campaigns, animations, and changing-state pages |
| Performance panel | Flame chart for long tasks, timeline for resource loading order, frame-by-frame layout shift analysis |
| Network panel | Request count/total size/TTFB/queue time — determine if CDN/prefetch/HTTP2 is needed |
Key Analysis Paths:
- FCP appears late → Check JS/CSS load time; for SSR check server API latency
- Long gap between FP and FCP → Check long tasks blocking rendering
- Large gap between FCP and LCP → Too many or too large viewport resources; SSR underutilized
- CLS spikes multiple times → Total > 0.25 needs priority fix
| 工具模式 | 使用场景 |
|---|---|
| Lighthouse导航模式 | 单页面从请求到加载完成的全流程分析 |
| Lighthouse时间段模式 | SPA路由切换与表单交互的INP/CLS分析 |
| Lighthouse快照模式 | 活动页、动画页与状态变化页面的分析 |
| 性能面板 | 长任务火焰图、资源加载顺序时间线、逐帧布局偏移分析 |
| 网络面板 | 请求数/总大小/TTFB/排队时间——判断是否需要CDN/预取/HTTP2 |
核心分析路径:
- FCP出现较晚→检查JS/CSS加载时间;SSR场景检查服务器API延迟
- FP与FCP间隔较长→检查阻塞渲染的长任务
- FCP与LCP间隔较大→视口资源过多或过大;SSR未充分利用
- CLS多次突增→总和>0.25需优先修复
Manual Measurement Requirement
手动测量要求
- By default, treat Lighthouse and Performance evidence as manually collected data
- Prefer measuring the same page/route 2–3 times and using the median result
- Record device type, browser version, network condition, and whether the page is SPA / SSR / SSG
- If possible, keep the measurement environment stable between before/after comparisons
- 默认将Lighthouse与性能面板的证据视为手动采集的数据
- 建议对同一页面/路由测量2–3次,取中位数结果
- 记录设备类型、浏览器版本、网络条件,以及页面是否为SPA/SSR/SSG
- 若可能,前后对比时保持测量环境稳定
Recommended manual collection flow
推荐手动采集流程
- Open Chrome DevTools
- Run Lighthouse manually for the target page or route
- Record the key metrics: LCP / FCP / INP / CLS / TTFB
- Open the Performance panel and manually record a trace for the same scenario
- Use the Network panel to confirm TTFB, request waterfalls, and heavy resources
- Keep screenshots or exported traces as evidence for before/after comparison
- 打开Chrome DevTools
- 手动对目标页面或路由运行Lighthouse
- 记录关键指标:LCP/FCP/INP/CLS/TTFB
- 打开性能面板,手动录制同一场景的追踪数据
- 使用网络面板确认TTFB、请求瀑布图与大体积资源
- 保留截图或导出的追踪数据作为前后对比的证据
If Manual Measurement Is Missing
若缺少手动测量数据
If the user has no manual Lighthouse or Performance measurements yet, do not claim a root cause with certainty.
Instead:
- Explicitly state that the diagnosis is inferred without manual measurement
- Give hypothesis-based suggestions according to visible symptoms, code structure, and page type
- Label each suggestion with the metric it is most likely to improve
- Recommend manually measuring Lighthouse and Performance after the change
如果用户尚未进行手动Lighthouse或性能面板测量,请勿断言根本原因。
应采取以下方式:
- 明确说明诊断是无手动测量的推断结果
- 根据可见症状、代码结构与页面类型给出基于假设的建议
- 为每条建议标注最可能改善的指标
- 建议优化后手动测量Lighthouse与性能面板
Suggested fallback advice without manual data
无手动数据时的 fallback 建议
- If the page visibly shows a long white screen → prioritize suggestions
FCP - If the hero image or first screen content appears late → prioritize suggestions
LCP - If clicking or typing feels delayed → prioritize /
INPsuggestionsTBT - If the page jumps during load → prioritize suggestions
CLS - If the whole page starts slowly before any content appears → prioritize suggestions
TTFB
These recommendations are best-effort hypotheses, not verified conclusions.
- 若页面明显显示长时间白屏→优先采用相关建议
FCP - 若首屏英雄图或内容出现较晚→优先采用相关建议
LCP - 若点击或输入感觉延迟→优先采用/
INP相关建议TBT - 若页面加载时出现跳转→优先采用相关建议
CLS - 若页面在任何内容出现前整体启动缓慢→优先采用相关建议
TTFB
这些建议是尽最大努力的假设,而非经过验证的结论。
Standalone Usage Mode
独立使用模式
This Skill contains executable judgment criteria, optimization strategies, code examples, and external service implementation patterns. It can be used independently without requiring access to any course documents.
本Skill包含可执行的判断标准、优化策略、代码示例及外部服务实现方案。无需依赖任何课程文档即可独立使用。
Standard Execution Flow
标准执行流程
- Collect current state
- Get core metrics: LCP/FCP/INP/CLS/TTFB (at least P75 and daily average)
- Gather evidence from manual Lighthouse + Performance + Network measurements
- Determine priority
- Fix worst metrics (Poor) first, then Needs Improvement
- Suggested order: (adjust per business needs)
FCP → LCP → CLS → INP → TTFB
- Match strategy
- Follow this Skill's diagnostic decision tree to select the corresponding optimization branch
- For external services, prefer the "Practical Examples" section above
- Implement & verify
- Small incremental commits; one type of optimization per change
- If possible, re-test 2–3 times using median values to confirm real improvement
- Document & prevent regression
- Record metrics before and after changes
- Consider adding key checks to CI (Lighthouse / performance budgets)
- 收集当前状态
- 获取核心指标:LCP/FCP/INP/CLS/TTFB(至少P75与日均值)
- 收集手动Lighthouse+性能面板+网络面板的证据
- 确定优先级
- 先修复最差指标(较差),再处理需要改进的指标
- 建议顺序:(可根据业务需求调整)
FCP → LCP → CLS → INP → TTFB
- 匹配策略
- 遵循本Skill的诊断决策树选择对应的优化分支
- 涉及外部服务时,优先参考上方「实践示例」部分
- 实施与验证
- 小步增量提交;每次变更仅做一类优化
- 若可能,重新测试2–3次取中位数,确认真实改善
- 记录与防回归
- 记录优化前后的指标
- 考虑将关键检查加入CI(Lighthouse / 性能预算)
Delivery Template
交付模板
markdown
undefinedmarkdown
undefinedOptimization Target
优化目标
- Page/Feature:
- Target Metric:
- Current Value:
- Target Value:
- 页面/功能:
- 目标指标:
- 当前值:
- 目标值:
Evidence
证据
- Manual Lighthouse evidence:
- Manual Performance evidence:
- Network evidence:
- 手动Lighthouse证据:
- 手动性能面板证据:
- 网络面板证据:
Execution Strategy
执行策略
- Approach:
- External services involved:
- Risk & rollback:
- 方案:
- 涉及外部服务:
- 风险与回滚:
Result Verification
结果验证
- Before:
- After:
- Conclusion:
undefined- 优化前:
- 优化后:
- 结论:
undefinedUsage Constraints
使用约束
- Don't sacrifice core functionality correctness for perceived speed
- Don't treat a single user's anomaly as a global performance issue
- Don't claim optimization success without verification
- If manual Lighthouse / Performance measurement is missing, clearly mark the advice as inferred and recommend follow-up validation
- 不要为了感知到的速度牺牲核心功能正确性
- 不要将单个用户的异常视为全局性能问题
- 没有验证不要宣称优化成功
- 若缺少手动Lighthouse/性能面板测量,需明确标注建议为推断结果,并推荐后续验证