frontend-fullchain-optimization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Frontend 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

指标阈值速查

MetricGoodNeeds ImprovementPoorUnitFocus
LCP≤ 2.5s2.5s - 4s> 4sTimeLargest Contentful Paint
FCP≤ 1.8s1.8s - 3s> 3sTimeFirst Contentful Paint
INP≤ 200ms200ms - 500ms> 500msTimeInteraction to Next Paint
CLS≤ 0.10.1 - 0.25> 0.25ScoreVisual Stability
TTFB≤ 800ms800ms - 1.8s> 1.8sTimeTime to First Byte
FID≤ 100ms100ms - 300ms> 300msTimeFirst Input Delay
TBTTasks > 50ms are long tasksTimeTotal 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.5s2.5s - 4s> 4s时间最大内容绘制(Largest Contentful Paint)
FCP≤ 1.8s1.8s - 3s> 3s时间首次内容绘制(First Contentful Paint)
INP≤ 200ms200ms - 500ms> 500ms时间交互到下一次绘制(Interaction to Next Paint)
CLS≤ 0.10.1 - 0.25> 0.25分数视觉稳定性(Visual Stability)
TTFB≤ 800ms800ms - 1.8s> 1.8s时间首字节时间(Time to First Byte)
FID≤ 100ms100ms - 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 required
text
页面加载缓慢?
├── 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:
MethodMechanismUse Case
setTimeout(fn, 0)
Creates a new macrotask at the end of the queueNon-urgent network requests, DB operations
Promise.resolve().then(fn)
Creates a microtask, runs immediately after current macrotaskSecondary tasks needing faster execution
requestAnimationFrame(fn)
Runs before next repaintRendering-related tasks
requestIdleCallback(fn)
Lowest priority, runs when main thread is idleAnalytics, logging
scheduler.postTask(fn, {priority})
Fine-grained priority controlScenarios requiring precise scheduling
postTask priorities:
user-blocking
(high) >
user-visible
(medium) >
background
(low)
Layout & Rendering Optimization:
  • Reduce
    calc()
    usage frequency; avoid unnecessary pseudo-class selectors (
    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
    <div>
    wrappers
  • 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
    table
    layout; reduce deeply nested CSS selectors
  • Use GPU-accelerated animations:
    transform
    /
    opacity
    trigger compositing layer; avoid
    top
    /
    left
    which trigger reflow
  • Use semantic HTML elements; avoid meaningless tags (e.g., use
    <button>
    not
    <div>
    for buttons)
诊断方法:Chrome性能面板——查找长任务(>50ms,红色高亮);在火焰图中检查事件处理程序的耗时。
策略——将长任务拆分为短任务
方法机制使用场景
setTimeout(fn, 0)
在队列末尾创建新的宏任务非紧急网络请求、数据库操作
Promise.resolve().then(fn)
创建微任务,在当前宏任务完成后立即执行需要更快执行的次要任务
requestAnimationFrame(fn)
在下一次重绘前执行渲染相关任务
requestIdleCallback(fn)
最低优先级,主线程空闲时执行埋点统计、日志记录
scheduler.postTask(fn, {priority})
细粒度优先级控制需要精确调度的场景
postTask优先级
user-blocking
(高)>
user-visible
(中)>
background
(低)
布局与渲染优化:
  • 减少
    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优化:
  • 避免
    table
    布局;减少深度嵌套的CSS选择器
  • 使用GPU加速动画:
    transform
    /
    opacity
    触发合成层;避免使用
    top
    /
    left
    (会触发重排)
  • 使用语义化HTML元素;避免无意义标签(例如按钮使用
    <button>
    而非
    <div>

TTFB Optimization (Network & Server)

TTFB优化(网络与服务器)

Diagnostic formula:
TTFB ≈ HTTP request time + Server processing time + HTTP response time
Diagnosis: 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.
DirectionStrategy
GeneralCDN acceleration (solves 90%+; proactively purge CDN cache after deploys), HTTP/2 multiplexing, Gzip compression, code splitting & dynamic imports
UXWeb Workers for heavy requests, DNS prefetch
<link rel="dns-prefetch">
, preconnect
<link rel="preconnect">
Server (SSR)Internal network for APIs, Redis cache for low-frequency data, reduce redirects, pre-generate static pages at build time
Resource CachingApp 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预取
<link rel="dns-prefetch">
、预连接
<link rel="preconnect">
服务器(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 time
White screen time ≈ FCP time. Target: instant open (< 1s).
StrategyDetails
Remove render-blocking resourcesAdd
defer
or
async
to script tags; non-critical JS → NPM bundle or framework components (e.g.,
next/script
)
Reduce JS/CSS sizeRemove unused code, Tree Shaking, code splitting
Control network payloadCompress above-fold images, use WebP/AVIF, lazy-load videos with placeholders
Caching strategy
Cache-Control: max-age=31536000
(static assets cached 1 year); JS/CSS as needed
Shorten critical request depthReduce nested resource dependencies (e.g., CSS @import chains); flatten critical resource request chains
Font optimizationSee "Font Optimization Strategies" below
White screen solutionsPWA (international markets); App hot-update local loading (domestic markets)
诊断公式
FCP ≈ TTFB + 资源下载时间 + DOM解析时间 + 渲染时间
白屏时间≈FCP时间。目标:秒开(<1s)。
策略细节
移除渲染阻塞资源为script标签添加
defer
async
;非关键JS移至NPM包或框架组件(例如
next/script
缩小JS/CSS体积移除未使用代码、Tree Shaking、代码分割
控制网络负载压缩首屏图片、使用WebP/AVIF格式、视频懒加载并添加占位符
缓存策略
Cache-Control: max-age=31536000
(静态资源缓存1年);JS/CSS按需设置
缩短关键请求链减少嵌套资源依赖(例如CSS @import链);扁平化关键资源请求链
字体优化查看下方「字体优化策略」
白屏解决方案海外市场用PWA;国内市场用应用热更新本地加载

Font Optimization Strategies

字体优化策略

ApproachDescription
Limit font countUse only one custom font + system font fallback; don't use different Web Fonts for body and p
Prefer WOFF230% better compression than WOFF, supported by all modern browsers
unicode-range
subsetting
Define character ranges (e.g., CJK U+4E00-9FA5); browser downloads only needed subsets
local()
local fonts
For apps with bundled fonts:
src: local('Font Name'), url(...)
reads local font first, no network request
font-display
strategy
swap
: system font first then replace (lowest CLS);
optional
: with preload (no re-layout on failure);
block
: wait (blocks rendering);
fallback
/
auto
: compromise
CSS Font Loading API
new FontFace()
+
font.load()
+
document.fonts.ready.then()
— programmatic control of font download timing and swap logic
Slow network fallbackUse
navigator.connection
to detect; slow users get system default fonts
方案说明
限制字体数量仅使用一种自定义字体+系统字体兜底;正文和段落不要使用不同的Web Fonts
优先使用WOFF2比WOFF压缩率高30%,所有现代浏览器均支持
unicode-range
子集化
定义字符范围(例如中日韩U+4E00-9FA5);浏览器仅下载所需子集
local()
本地字体
内置字体的应用:
src: local('Font Name'), url(...)
优先读取本地字体,无需网络请求
font-display
策略
swap
:先显示系统字体再替换(CLS最低);
optional
:配合预加载(加载失败不重排);
block
:等待(阻塞渲染);
fallback
/
auto
:折中方案
CSS Font Loading API
new FontFace()
+
font.load()
+
document.fonts.ready.then()
— 程序化控制字体下载时机与替换逻辑
慢网络兜底使用
navigator.connection
检测;慢网络用户使用系统默认字体

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:
  1. <img>
    elements (most common) and
    <image>
    within SVG
  2. <video>
    poster
    attribute image or first frame
  3. Elements with CSS
    url()
    background images
  4. 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
StrategyDetails
Preload LCP image
<link rel="preload" href="..." as="image">
Framework image componentsUse
next/image
(includes priority & format optimization); set
priority={true}
Split large imagesSlice large background images into smaller pieces
Image formatPNG/JPEG → WebP/AVIF, saves 30%+ size
Cloud image paramsDynamically set image size/quality/format per device (e.g., Alibaba Cloud OSS params)
Rich text imagesExtract image URLs from content, set
<link rel="preload">
in advance
Avoid duplicate preloadsWhen using framework image components (e.g.,
next/image
) with
priority
, don't also add manual
<link rel="preload">
— duplicates waste bandwidth
Sampling advice: PV < 1M → full LCP collection; above that → ratio sampling or threshold-based reporting.
诊断方法:性能面板——找到LCP标记元素;Lighthouse报告中的「Largest Contentful Paint element」条目。
LCP可标记的4类元素:
  1. <img>
    元素(最常见)及SVG内的
    <image>
  2. <video>
    poster
    属性图片或第一帧
  3. 带有CSS
    url()
    背景图的元素
  4. 包含文本节点的块级元素
关键结论:
  • LCP时间始终≥FCP时间
  • 若TTFB和FCP正常但LCP异常→问题出在视口资源加载
  • SPA:FCP比LCP更重要;SSR/MPA:LCP比FCP更重要
策略细节
预加载LCP图片
<link rel="preload" href="..." as="image">
框架图片组件使用
next/image
(包含优先级与格式优化);设置
priority={true}
拆分大图将大型背景图切割为小块
图片格式PNG/JPEG→WebP/AVIF,体积减少30%+
云图片参数根据设备动态设置图片尺寸/质量/格式(例如阿里云OSS参数)
富文本图片从内容中提取图片URL,提前设置
<link rel="preload">
避免重复预加载使用带
priority
的框架图片组件(例如
next/image
)时,不要手动添加
<link rel="preload">
——重复预加载会浪费带宽
采样建议:PV<1M→全量采集LCP;超过该值→比例采样或基于阈值上报。

CLS Optimization (Layout Shift)

CLS优化(布局偏移)

Diagnostic formula:
Layout shift score = Impact fraction × Distance fraction
,
CLS = SUM(all shift scores)
Key conclusion: The farther the element shifts + the more viewport area affected → higher CLS.
ScenarioOptimization Strategy
ImagesSet
width
/
height
on all
<img>
; use
aspect-ratio
for mobile; use
srcset
/
<picture>
for responsive images
Dynamic contentReserve fixed-size placeholder containers for ads/iframes; avoid inserting content at top of viewport without interaction; inserting near bottom has less CLS impact
CSS animationsUse
transform
instead of
top/left/width/height
; use
transform: scale()
instead of changing dimensions
Fonts
font-display: optional
+ preload; or
font-display: swap
to reduce CLS impact
诊断公式
布局偏移分数 = 影响比例 × 距离比例
CLS = 所有偏移分数之和
核心结论:元素偏移距离越远+影响的视口面积越大→CLS值越高。
场景优化策略
图片为所有
<img>
设置
width
/
height
;移动端使用
aspect-ratio
;响应式图片使用
srcset
/
<picture>
动态内容为广告/iframe预留固定尺寸的占位容器;避免无交互时在视口顶部插入内容;在底部附近插入对CLS影响更小
CSS动画使用
transform
替代
top/left/width/height
;使用
transform: scale()
替代修改尺寸
字体
font-display: optional
+预加载;或使用
font-display: swap
降低CLS影响

General Optimization Tips

通用优化技巧

TipDescription
Network awareness
navigator.connection.effectiveType
to detect 2G/3G/4G; degrade for slow users (smaller images, system fonts, less loading)
SVG iconsAll small icons (< 5KB / < 50px) should use SVG instead of images to reduce async requests
Responsive degradationCSS media queries split CSS by screen size; skip background images on small screens
Cache-firstCache list data in LocalStorage; render cache first then async refresh to reduce white screen
Request mergingMerge resources, reduce HTTP request count and domain count
Rendering modeChoose SSR (fast first paint) / CSR (strong interactivity) / SSG (static content) by scenario
技巧说明
网络感知
navigator.connection.effectiveType
检测2G/3G/4G;慢网络用户降级(更小图片、系统字体、更少加载内容)
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
undefined

Executed 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" ] }'
undefined
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" ] }'
undefined

Example 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 ModeUse Case
Lighthouse Navigation modeFull process analysis from request to load complete for a single page
Lighthouse Timespan modeINP/CLS analysis for SPA route transitions and form interactions
Lighthouse Snapshot modeAnalysis of campaigns, animations, and changing-state pages
Performance panelFlame chart for long tasks, timeline for resource loading order, frame-by-frame layout shift analysis
Network panelRequest count/total size/TTFB/queue time — determine if CDN/prefetch/HTTP2 is needed
Key Analysis Paths:
  1. FCP appears late → Check JS/CSS load time; for SSR check server API latency
  2. Long gap between FP and FCP → Check long tasks blocking rendering
  3. Large gap between FCP and LCP → Too many or too large viewport resources; SSR underutilized
  4. CLS spikes multiple times → Total > 0.25 needs priority fix
工具模式使用场景
Lighthouse导航模式单页面从请求到加载完成的全流程分析
Lighthouse时间段模式SPA路由切换与表单交互的INP/CLS分析
Lighthouse快照模式活动页、动画页与状态变化页面的分析
性能面板长任务火焰图、资源加载顺序时间线、逐帧布局偏移分析
网络面板请求数/总大小/TTFB/排队时间——判断是否需要CDN/预取/HTTP2
核心分析路径:
  1. FCP出现较晚→检查JS/CSS加载时间;SSR场景检查服务器API延迟
  2. FP与FCP间隔较长→检查阻塞渲染的长任务
  3. FCP与LCP间隔较大→视口资源过多或过大;SSR未充分利用
  4. 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

推荐手动采集流程

  1. Open Chrome DevTools
  2. Run Lighthouse manually for the target page or route
  3. Record the key metrics: LCP / FCP / INP / CLS / TTFB
  4. Open the Performance panel and manually record a trace for the same scenario
  5. Use the Network panel to confirm TTFB, request waterfalls, and heavy resources
  6. Keep screenshots or exported traces as evidence for before/after comparison
  1. 打开Chrome DevTools
  2. 手动对目标页面或路由运行Lighthouse
  3. 记录关键指标:LCP/FCP/INP/CLS/TTFB
  4. 打开性能面板,手动录制同一场景的追踪数据
  5. 使用网络面板确认TTFB、请求瀑布图与大体积资源
  6. 保留截图或导出的追踪数据作为前后对比的证据

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:
  1. Explicitly state that the diagnosis is inferred without manual measurement
  2. Give hypothesis-based suggestions according to visible symptoms, code structure, and page type
  3. Label each suggestion with the metric it is most likely to improve
  4. Recommend manually measuring Lighthouse and Performance after the change
如果用户尚未进行手动Lighthouse或性能面板测量,请勿断言根本原因。
应采取以下方式:
  1. 明确说明诊断是无手动测量的推断结果
  2. 根据可见症状、代码结构与页面类型给出基于假设的建议
  3. 为每条建议标注最可能改善的指标
  4. 建议优化后手动测量Lighthouse与性能面板

Suggested fallback advice without manual data

无手动数据时的 fallback 建议

  • If the page visibly shows a long white screen → prioritize
    FCP
    suggestions
  • If the hero image or first screen content appears late → prioritize
    LCP
    suggestions
  • If clicking or typing feels delayed → prioritize
    INP
    /
    TBT
    suggestions
  • If the page jumps during load → prioritize
    CLS
    suggestions
  • If the whole page starts slowly before any content appears → prioritize
    TTFB
    suggestions
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

标准执行流程

  1. 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
  2. Determine priority
    • Fix worst metrics (Poor) first, then Needs Improvement
    • Suggested order:
      FCP → LCP → CLS → INP → TTFB
      (adjust per business needs)
  3. Match strategy
    • Follow this Skill's diagnostic decision tree to select the corresponding optimization branch
    • For external services, prefer the "Practical Examples" section above
  4. 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
  5. Document & prevent regression
    • Record metrics before and after changes
    • Consider adding key checks to CI (Lighthouse / performance budgets)
  1. 收集当前状态
    • 获取核心指标:LCP/FCP/INP/CLS/TTFB(至少P75与日均值)
    • 收集手动Lighthouse+性能面板+网络面板的证据
  2. 确定优先级
    • 先修复最差指标(较差),再处理需要改进的指标
    • 建议顺序:
      FCP → LCP → CLS → INP → TTFB
      (可根据业务需求调整)
  3. 匹配策略
    • 遵循本Skill的诊断决策树选择对应的优化分支
    • 涉及外部服务时,优先参考上方「实践示例」部分
  4. 实施与验证
    • 小步增量提交;每次变更仅做一类优化
    • 若可能,重新测试2–3次取中位数,确认真实改善
  5. 记录与防回归
    • 记录优化前后的指标
    • 考虑将关键检查加入CI(Lighthouse / 性能预算)

Delivery Template

交付模板

markdown
undefined
markdown
undefined

Optimization 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
  • 优化前:
  • 优化后:
  • 结论:
undefined

Usage 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/性能面板测量,需明确标注建议为推断结果,并推荐后续验证