Web 性能
Optimize web 性能 — 加载, 渲染, 镜像, and 核心 Web Vitals.
你将学到
- 为什么性能 matters for 用户 experience and SEO rankings
- 核心 Web Vitals: LCP, FID/INP, and CLS — 什么它们 measure
- 技巧: code 拆分, lazy 加载, 镜像 optimization, 缓存
- 如何 measure 性能使用 Lighthouse and 性能 API
概念讲解
Web Performance
Web performance is how fast your page loads and how smoothly it responds to user input. It matters because users leave slow pages — studies show that a 1-second delay can reduce conversions by 7%. Google also uses performance as a ranking factor, so slow pages rank lower. Performance is not a one-time optimization but an ongoing discipline: measure, optimize, re-measure.
Core Web Vitals
Google's Core Web Vitals are three metrics that summarize the user experience:
- LCP (Largest Contentful Paint) — when the largest visible element renders. Target: under 2.5 seconds. Measures *loading*.
- INP (Interaction to Next Paint) — the time from a user interaction to the next visual update. Target: under 200 milliseconds. Measures *interactivity*. (Replaces FID in 2024.)
- CLS (Cumulative Layout Shift) — how much the layout shifts unexpectedly as the page loads. Target: under 0.1. Measures *visual stability*.
A good score on all three means the page loads fast, responds quickly, and does not jump around. You can see your scores in Chrome DevTools (Lighthouse tab) or in the Chrome User Experience Report.
Loading Optimization
- Minify and compress — remove whitespace and comments from CSS/JS, and enable gzip or Brotli compression on the server. Brotli is ~20% smaller than gzip.
- Code splitting — load only the JavaScript needed for the current page. Modern bundlers (Webpack, Vite) split code automatically with dynamic imports.
- Lazy loading — defer non-critical resources. Use
加载="lazy"on images below the fold. Load third-party scripts (analytics, chat widgets) withdeferor after page load. - Caching — set
缓存-Controlheaders so the browser caches static assets. Use content hashing in filenames so cached files update when content changes.
Image Optimization
Images are usually the largest resources on a page. Optimize them:
- Use modern formats: WebP (smaller than JPEG/PNG) or AVIF (even smaller).
- Serve responsive images with
<img srcset>so phones get small images and desktops get large ones. - Set explicit
宽度and高度attributes to prevent layout shift (CLS). - Lazy-load images below the fold with
加载="lazy".
Rendering Optimization
- Reduce layout thrashing — avoid reading and writing DOM styles in a loop. Batch reads, then batch writes.
- Animate only transform and opacity — these do not trigger layout recalculation.
- Debounce scroll and resize handlers — these fire many times per second. Debounce to run at most once per frame.
- Use requestAnimationFrame for visual updates to sync with the browser's repaint cycle.
Measuring Performance
Use Lighthouse (in Chrome DevTools) for a comprehensive audit with actionable suggestions. Use the Performance API (性能.现在(), PerformanceObserver) for real-user monitoring in production. Track your Core Web Vitals over time — a one-time measurement is not enough; performance regresses as code grows.
示例代码
<!-- Responsive, lazy-loaded image with explicit dimensions -->
<img
src="hero-800.webp"
srcset="hero-400.webp 400w,
hero-800.webp 800w,
hero-1200.webp 1200w"
sizes="(max-width: 600px) 400px,
(max-width: 1000px) 800px,
1200px"
width="1200"
height="600"
loading="lazy"
decoding="async"
alt="A scenic mountain landscape"
/>
<!-- Deferred non-critical JavaScript -->
<script src="analytics.js" defer></script>
<!-- Preload the most important resource -->
<link rel="preload" as="image" href="hero-800.webp" />
<!-- Dynamic import for code splitting -->
<script>
// This chunk loads only when the user clicks
document.querySelector("#open-editor")
.addEventListener("click", async () => {
const { Editor } = await import("./editor.js");
new Editor().open();
});
</script>
镜像 uses srcset and 大小 for responsive delivery, explicit 宽度/高度到 prevent CLS, and 加载=lazy for deferred 加载. analytics script uses defer 所以它 做不 块渲染. preload 提示开始 hero 镜像 early. 动态导入加载 editor code 仅当 需要, 拆分 bundle.
动手试一试
- SVG Optimizer
Optimizing SVGs reduces file 大小 and improves 加载性能 — 动手试一试.
- 镜像颜色 Picker
理解镜像数据 helps 你选择 efficient 格式 and compression.
常见错误
错误写法
加载所有 JavaScript upfront in 单个大 bundle.
正确做法
Use code 拆分使用动态导入所以每个 page 加载仅 code 它需要. Modern bundlers handle 这个 automatically. Lazy-加载 below--fold 组件 and 第三-party scripts 使用 defer or 动态导入.
错误写法
Serving 完整-大小镜像 and relying on CSS 到 resize 它们.
正确做法
Use srcset and 大小 attributes 到 serve appropriately sized 镜像 for 每个 device. Use modern 格式 (WebP, AVIF). 设置 explicit 宽度 and 高度 attributes 到 prevent 布局 shift. Lazy-加载镜像 below fold.
相关资源
相关速查表
- CSS Cheatsheet
性能-friendly CSS: containment, 将-更改, and efficient selectors.
练习 Web 性能
4 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。