NOTE这个项目不给你”已经优化好的代码”,而是给你一个故意很慢的页面和一套测量方法。 你要自己改、自己量、自己填表。因为性能这件事,没有数字的优化等于没做。
对象页面:
perf-harness.html(下面会给你)。它同时踩了 5 个典型坑: 大图没尺寸、阻塞脚本、字体闪、长任务卡输入、图片延迟加载策略错误。
做到什么算过
- 能用
PerformanceObserver自己采到 LCP / CLS / INP,而不是只会看 Lighthouse 分数。 - 能搭出可复现的测量环境(固定网络/CPU 限速、固定视口、无缓存),别人按你的步骤能量出接近的数字。
- 能说清 LCP 的四个子阶段(TTFB → 资源加载 → 资源加载延迟 → 元素渲染),并指出当前卡在哪一段。
- 能把首屏 LCP 从 4s 级压到 2s 级,并给出改前/改后两张数字表。
- 能让 CLS 接近 0,并解释每个 0.1 是怎么来的(图片没尺寸?字体切换?横幅插入?)。
- 能把 INP 从”点一下卡 300ms”降到 200ms 以内,并说清是哪个长任务干的。
- 能识别”假优化”:加了
will-change、content-visibility却没有任何指标变化。 - 能写一份给团队的性能预算(体积/指标阈值),并接入 CI 或监控(见工程化那篇)。
阶段 1:先测量(没有基线就没有优化)
1. 搭一个”故意很慢”的页面
<!doctype html><html lang="zh-CN"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Perf Harness</title> <!-- ❌ 坑 1:同步脚本挡住解析 --> <script src="./heavy-blocking.js"></script> <style> body { margin: 0; font-family: "Inter", system-ui, sans-serif; } .hero { padding: 24px; } /* ❌ 坑 2:首屏大图没有尺寸 → CLS */ .hero img { width: 100%; } /* ❌ 坑 3:字体没有 font-display,文字先隐形再切换 → CLS + 闪 */ @font-face { font-family: "Inter"; src: url("/fonts/Inter.woff2") format("woff2"); } .banner { height: 0; overflow: hidden; transition: height 0.2s; } .banner.open { height: 160px; } </style> </head> <body> <div class="hero"> <h1>毕业项目:性能优化</h1> <!-- 首屏图:没有 width/height、没有 fetchpriority --> <img src="/img/hero-2400.jpg" alt="首屏大图" /> <p>下面这块内容会在 1.2 秒后插入一个横幅——没有预留空间,必然造成布局位移。</p> </div> <div id="banner-root"></div> <!-- ❌ 坑 4:一次性渲染 5000 个节点 + 一个 300ms 的同步计算 --> <button id="compute">点我(会卡)</button> <ul id="list"></ul> <script type="module" src="./perf-harness.js"></script> </body></html>// ❌ 坑 5:长任务 + 大 DOMconst list = document.querySelector("#list");const frag = document.createDocumentFragment();for (let i = 0; i < 5000; i++) { const li = document.createElement("li"); li.textContent = `第 ${i + 1} 条数据`; frag.append(li);}list.append(frag);
document.querySelector("#compute").addEventListener("click", () => { const start = performance.now(); let sum = 0; while (performance.now() - start < 300) sum += Math.random(); // 故意的长任务 console.log("done", sum);});
// 1.2s 后插入横幅(不预留空间 → CLS)setTimeout(() => { const el = document.createElement("div"); el.className = "banner open"; el.textContent = "活动横幅"; document.querySelector("#banner-root").append(el);}, 1200);2. 自己采指标(不依赖任何库)
// perf-metrics.js —— 在任何页面引入即可,控制台会打印三个核心指标const report = (name, value, extra = {}) => console.log(`[perf] ${name} = ${Math.round(value * 1000) / 1000}`, extra);
// LCP:每次有更大的元素被渲染就更新,用户首次交互或页面隐藏后停止let lcp = 0;new PerformanceObserver((list) => { const entries = list.getEntries(); const last = entries[entries.length - 1]; if (last) { lcp = last.startTime; report("LCP", lcp, { element: last.element?.tagName, url: last.url }); }}).observe({ type: "largest-contentful-paint", buffered: true });
// CLS:累加没有用户输入的位移(有输入的位移不算)let cls = 0;new PerformanceObserver((list) => { for (const entry of list.getEntries()) { if (!entry.hadRecentInput) cls += entry.value; } report("CLS", cls);}).observe({ type: "layout-shift", buffered: true });
// INP:记录每次交互的耗时,取最差的一次(简化版)const interactions = [];new PerformanceObserver((list) => { for (const entry of list.getEntries()) interactions.push(entry.duration); const worst = Math.max(...interactions); report("INP(近似)", worst, { count: interactions.length });}).observe({ type: "event", buffered: true, durationThreshold: 16 });
// 长任务:定位"卡"的元凶new PerformanceObserver((list) => { for (const entry of list.getEntries()) { report("longtask", entry.duration, { start: Math.round(entry.startTime) }); }}).observe({ type: "longtask", buffered: true });3. 可复现的测量环境(这一节最关键)
视口:390×844(移动)或 1440×900(桌面),固定不缩放网络:Slow 4G(下行 1.6Mbps / 上行 750kbps / RTT 150ms)CPU:4× 降速缓存:Disable cache 勾选运行:每次硬刷新 3 次,取中位数命令行(无头,可脚本化):
chrome --headless=new --disable-gpu \ --user-data-dir=/tmp/perf-profile \ --window-size=390,844 \ --force-device-scale-factor=1 \ --disable-application-cache \ --screenshot=/tmp/before.png \ http://localhost:8080/perf-harness.html有 CDP 更好:
Emulation.setDeviceMetricsOverride+Network.emulateNetworkConditions+Emulation.setCPUThrottlingRate,这样”改前/改后”一定在同一条件下测。
4. 基线表(必须填,不填不算做完)
| 指标 | 含义 | 基线 | 目标 | 改后 |
|---|---|---|---|---|
| LCP | 首屏最大内容渲染完 | ___ s | ≤ 2.0s | ___ s |
| CLS | 累计布局位移 | ___ | ≤ 0.1 | ___ |
| INP | 交互响应(近似) | ___ ms | ≤ 200ms | ___ ms |
| TBT | 主线程阻塞总时长 | ___ ms | ≤ 300ms | ___ ms |
| 传输体积 | 首屏加载字节 | ___ KB | ≤ 500KB | ___ KB |
| 请求数 | 首屏请求数 | ___ | ≤ 40 | ___ |
✅ 阶段 1 验收清单
- 控制台能稳定打印 LCP/CLS/INP/longtask 四类日志。
- 同一个页面连续测 3 次,LCP 波动在 ±10% 内(条件固定了才会稳)。
- 能指出 LCP 元素是什么(控制台里
element字段),以及它卡在哪一段(看 Network 里那张图的时间条)。 - 能说出 CLS 的 0.2 分别来自哪两处位移(点开 Performance → Experience 轨道)。
- 能指出最长的那条长任务是多少毫秒、由什么触发(点击 or 首屏脚本)。
- 基线表已填满(哪怕是难看的数字)。
阶段 2:加载路径(主攻 LCP)
LCP 拆成四段看:TTFB → 资源加载延迟 → 资源加载时长 → 元素渲染。先定位卡在哪段,再动手。
1. 首屏图:把”延迟”和”尺寸”都解决
<!-- ❌ 改前 --><img src="/img/hero-2400.jpg" alt="首屏大图" />
<!-- ✅ 改后 --><img src="/img/hero-1200.avif" srcset="/img/hero-800.avif 800w, /img/hero-1200.avif 1200w, /img/hero-1600.avif 1600w" sizes="(max-width: 600px) 100vw, 1200px" width="1200" height="675" fetchpriority="high" decoding="async" alt="首屏大图"/>四个改动的分别作用:
| 改动 | 解决什么 |
|---|---|
width/height(或 aspect-ratio) | 图片加载前就占好位 → CLS 归零 |
srcset/sizes + AVIF | 手机不再下 2400px 大图 → 加载时间降一个量级 |
fetchpriority="high" | 提升该资源的网络优先级,不被后面的 JS 挤后 |
decoding="async" | 解码不阻塞主线程 |
注意:loading="lazy" 不要加在首屏图上——那会故意推迟 LCP 图,是常见的反向优化。
2. 非首屏图:懒加载 + 占位
<img src="/img/list-1.jpg" width="480" height="320" loading="lazy" decoding="async" alt="列表图" />/* 没写宽高时的兜底:至少给个比例,避免塌陷 */.card-media { aspect-ratio: 3 / 2; background: #eee; }3. 字体:先能读,再好看
@font-face { font-family: "Inter"; src: url("/fonts/Inter-subset.woff2") format("woff2"); font-display: swap; /* 关键:先用系统字体渲染,字体到了再换 */ unicode-range: U+0000-00FF; /* 只含拉丁字符,中文用系统字体 */ size-adjust: 100%; /* 需要时用 fallback 度量对齐,减少切换抖动 */}<!-- 只 preload 真正首屏要用的那一个字体/一个字重,别 preload 全家桶 --><link rel="preload" href="/fonts/Inter-subset.woff2" as="font" type="font/woff2" crossorigin />4. 阻塞资源:把不该挡路的挪开
<!-- ❌ 同步阻塞解析 --><script src="./heavy-blocking.js"></script>
<!-- ✅ 模块脚本天然 defer;普通脚本显式 defer --><script type="module" src="./app.js"></script><script defer src="./analytics.js"></script><!-- 关键 CSS 内联,其余异步 --><style>/* 首屏必需的样式,通常 < 3KB */</style><link rel="preload" href="/css/app.css" as="style" onload="this.rel='stylesheet'" /><noscript><link rel="stylesheet" href="/css/app.css" /></noscript><!-- 提前建连:图片/字体 CDN --><link rel="preconnect" href="https://img.example.com" crossorigin />✅ 阶段 2 验收清单
- 首屏图请求的
priority变成 High(Network 面板的 Priority 列),并且不再下 2400px 原图。 - 图片加载前容器就有高度,滚动过程中 CLS 不再增加。
- 移除首屏图上的
loading="lazy"后 LCP 变好(用来证明这条不是玄学)。 - 字体加载期间文字可见(不出现 3 秒空白),字体切换时 CLS 增幅 < 0.01。
- 首屏请求数、传输体积较基线下降(把两个数字填进表)。
- LCP 至少下降 30%(若没有,说明 LCP 瓶颈不在网络/图片,回头重新定位)。
阶段 3:运行时(主攻 INP 与 CLS)
1. 长任务:让出主线程
// ❌ 一次性渲染 5000 条,主线程卡 300ms+list.append(frag);
// ✅ 分批插入,每批之间让浏览器喘息(先渲染,再继续)async function renderInBatches(items, batchSize = 200) { for (let i = 0; i < items.length; i += batchSize) { const frag = document.createDocumentFragment(); for (const item of items.slice(i, i + batchSize)) { const li = document.createElement("li"); li.textContent = item; frag.append(li); } list.append(frag); // 让出主线程:浏览器有机会渲染 + 处理输入 await new Promise((r) => setTimeout(r, 0)); }}
scheduler.yield()是更现代的做法(Chrome 129+)。降级写法就是上面的setTimeout(0);不要用requestAnimationFrame做”让出”,它仍然在同一帧里。
2. 事件处理:先读后写,别制造同步布局
// ❌ 读-写-读-写 交替 → 每次都强制同步布局(Layout Thrashing)for (const el of items) { const h = el.offsetHeight; // 读 → 触发布局 el.style.height = h + 10 + "px"; // 写 → 布局失效}
// ✅ 批量读、批量写const heights = items.map((el) => el.offsetHeight);items.forEach((el, i) => { el.style.height = heights[i] + 10 + "px"; });3. 点击”卡 300ms”:把重活挪走
// ❌ 同步长计算btn.addEventListener("click", () => { const start = performance.now(); while (performance.now() - start < 300) sum += Math.random();});
// ✅ 先给反馈,再分片计算btn.addEventListener("click", async () => { btn.textContent = "计算中…"; // 立刻有反馈(INP 只算到首帧) await new Promise((r) => setTimeout(r, 0)); let sum = 0; for (let i = 0; i < 30; i++) { sum += await computeChunk(); // 每片 < 50ms btn.textContent = `计算中… ${Math.round(((i + 1) / 30) * 100)}%`; } btn.textContent = "完成";});4. CLS:横幅/图片/字体三类来源逐个消掉
/* 预留空间:横幅没数据时也占位,插入时不推内容 */.banner-slot { min-height: 160px; }
/* 动画只动 transform/opacity,不动 height/width/top */.banner { transform: translateY(-100%); transition: transform 0.2s; }.banner.open { transform: translateY(0); }5. 长列表:虚拟化或分页(真需要再上)
5000 条 DOM 会带来两个问题:初次渲染卡(长任务)+ 内存高。先分页/分批,确实需要无限滚动再上虚拟列表(固定行高 + 只渲染可视区 ± 缓冲)。
✅ 阶段 3 验收清单
- 首屏渲染的长任务从 300ms+ 降到没有超过 50ms 的长任务(Performance 面板确认)。
- 点按钮:首帧反馈 < 100ms(按钮立刻变”计算中…”),总耗时不影响 INP。
- INP 从 ___ ms 降到 ≤ 200ms,并填进表。
- 1.2s 插入横幅时 CLS 不再增加(
min-height占位生效)。 - 动画期间没有 Layout/Recalculate Style 的持续抖动(Performance 里只看到 Composite)。
- 5000 条列表滚动时帧率稳定(Performance 里无 > 50ms 长任务)。
- 反向验证:把
content-visibility: auto加上又去掉,记录指标是否真的变化——没变化就说明它是”假优化”,别写进报告。
最终交付:一张前后对比表 + 一段结论
| 指标 | 基线 | 改后 | 变化 |
|---|---|---|---|
| LCP | 4.2s | 1.8s | −57% |
| CLS | 0.24 | 0.02 | −92% |
| INP(近似) | 320ms | 140ms | −56% |
| TBT | 780ms | 210ms | −73% |
| 首屏传输 | 1.9MB | 480KB | −75% |
| 首屏请求数 | 63 | 31 | −51% |
上表是示例数值,你的数字一定不同。关键是每一行你都能解释”为什么变了”,以及改动对应哪一段(网络 / 渲染 / 交互)。
结论怎么写(模板):
LCP 主要受首屏图片支配:原图 2400px、无
srcset、无优先级,移动端要下 1.6MB。 换成srcset + AVIF + fetchpriority=high后,首屏图传输降到 180KB,LCP 从 4.2s → 1.8s。 CLS 的两处来源分别是”首屏图无尺寸”(0.18)与”横幅插入未预留”(0.06),加width/height与min-height后归零。 INP 的瓶颈是一个 320ms 的同步循环,改成分片 + 首帧反馈后降到 140ms。
常见坑
- 只看 Lighthouse 分数:分数是加权模型,不是用户感受;先看 LCP/CLS/INP 原始数字。
- 测前没关缓存:第二次测都是缓存命中,数字好得离谱。永远 Disable cache + 新 profile。
- 不同条件对比:改前用桌面、改后用移动,结论全废。
- 给首屏图加
loading="lazy":直接推迟 LCP,是最常见的反向优化。 preload全家桶:抢了关键资源的带宽,反而更慢。只 preload 首屏必需。font-display: block:文字最长隐形 3 秒,LCP 直接崩。content-visibility用在首屏内容上:首屏不渲染,LCP 变差;它适合长列表的”屏外”部分。will-change加一堆:每层都提升为合成层,显存和合成开销反而上升。- 只看首屏:交互卡顿(INP)往往比 LCP 更影响真实体验,别漏。
- 优化完不留监控:三个月后又被改回去。把预算接进 CI/监控才算闭环。
毕业自测:10 题
- LCP 的四个子阶段是什么?怎么从 Network + Performance 里判断卡在哪段?
- 为什么
width/height能消掉 CLS?(浏览器在图片到达前就知道占位高度) srcset和sizes分别告诉浏览器什么?fetchpriority与preload的区别?什么时候用哪个?font-display: swap的代价是什么?(字体切换时的抖动,可用size-adjust缓解)- 什么是长任务?阈值是多少?(> 50ms)
- 为什么”读-写-读-写”会触发多次布局?怎么批量?
- INP 只计算到哪一刻?(到下一次绘制,不是整个回调执行完)
content-visibility: auto有什么副作用?(锚点跳转、页内搜索、打印可能异常)- 你的性能预算打算怎么落进 CI?(体积用
size-limit;指标用真实用户监控 + 报警)
做完之后
- 你有了方法论:先测量 → 定位瓶颈 → 针对性改 → 再测量 → 填表。
- 你有了证据:一张前后对比表 + 每个数字的解释。
- 这套方法可以平移到任何项目:换页面、换框架,四步不变。
- 下一步:把指标接到真实用户监控(
navigator.sendBeacon上报 LCP/CLS/INP 到你的后端),再按 P75 分位数建立预算与报警。
性能的毕业标准:不靠感觉,靠数字;不只优化一次,而是让它不退化。