知其然,更知其所以然 | 课型:理论课 | 建议课时:2节
两个动画盒子对比:改left(重排卡顿)vs改transform(合成流畅)。
新窗口运行 下载源码<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>重排 vs 重绘</title>
<style>
body { font-family: "Microsoft YaHei", sans-serif; background: #f2f6f8; margin: 0; padding: 24px; }
.track { position: relative; height: 90px; background: #fff; border-radius: 10px; margin: 14px 0; overflow: hidden; }
.ball { position: absolute; top: 15px; left: 0; width: 60px; height: 60px; border-radius: 50%;
display: flex; align-items: center; justify-content: center; color: #fff; font-size: 13px; }
.bad { background: #c05a1e; animation: bad 2s linear infinite alternate; }
.good { background: #0f8c7f; animation: good 2s linear infinite alternate; }
@keyframes bad { to { left: calc(100% - 60px); } } /* 每帧触发布局 */
@keyframes good { to { transform: translateX(calc(100vw - 120px)); } } /* 只触发合成 */
.tag { font-size: 14px; color: #6b8a99; }
</style>
</head>
<body>
<h1>重排 vs 合成</h1>
<p class="tag">橙色:改变left(每帧重排)|绿色:改变transform(仅合成,GPU加速)</p>
<div class="track"><div class="ball bad">left</div></div>
<div class="track"><div class="ball good">transform</div></div>
<p class="tag">打开开发者工具→更多工具→Rendering→勾选"Frame Rendering Stats"对比帧率</p>
</body>
</html>任务目标:理解渲染原理并完成一次真实性能优化
| 任务内容与评分 |
|---|
| 任务1:画出渲染五步流程图(20分) |
| 任务2:用Paint flashing找出页面的重绘区域(15分) |
| 任务3:把一个left动画改写为transform(20分) |
| 任务4:为个人站点跑Lighthouse并截图四项分数(20分) |
| 任务5:完成三项优化(图片/脚本/缓存)并复测对比(25分) |