优化 CSS 性能,提升网页加载速度
| 类型 | 描述 | 影响 |
|---|---|---|
| 回流 (Reflow) | 布局发生变化,需要重新计算元素位置和大小 | 高,影响整个页面 |
| 重绘 (Repaint) | 外观发生变化,不需要重新计算布局 | 中,影响部分元素 |
/* 不好的做法 */
for (let i = 0; i < 1000; i++) {
element.style.left = i + 'px';
element.style.top = i + 'px';
}
/* 好的做法 */
element.style.transform = 'translate(' + i + 'px, ' + i + 'px)';<style> 标签中/* HTML 中内联关键 CSS */
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
.header {
background: #3498db;
color: white;
padding: 20px;
}
.hero {
height: 500px;
background: #f8f9fa;
display: flex;
align-items: center;
justify-content: center;
}
</style>
/* 异步加载其余 CSS */
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"</link></noscript>/* package.json */
{
"scripts": {
"build": "purgecss --css styles.css --content index.html --output purified.css"
}
}查看页面的图层信息,优化图层使用。
分析和调试动画性能。
分析页面加载和运行时性能。
/* 不好的做法 */
div.container > ul.menu > li.item > a.link {
color: #333;
}
/* 好的做法 */
.menu__link {
color: #333;
}/* 触发硬件加速 */
.element {
transform: translateZ(0);
will-change: transform;
}/* 压缩前 */
body {
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.6;
color: #333;
background: #fff;
}
/* 压缩后 */
body{font-family:Arial,sans-serif;font-size:16px;line-height:1.6;color:#333;background:#fff}