SVG 性能优化对于创建流畅、响应迅速的 Web 应用至关重要。本章节介绍各种优化技巧和最佳实践。
SVGOMG 是一个在线 SVG 优化工具,可以:
<!-- 优化前 -->
<svg width="100" height="100" version="1.1" baseProfile="full">
<rect x="10" y="10" width="50" height="50"/>
</svg>
<!-- 优化后 -->
<svg width="100" height="100">
<rect x="10" y="10" width="50" height="50"/>
</svg>相对坐标通常比绝对坐标更紧凑。
使用 <defs> 和 <use> 复用重复元素。
/* 好 */
.element {
transform: translate(100px, 100px);
}
/* 避免 */
.element {
left: 100px;
top: 100px;
}// 好
const fragment = document.createDocumentFragment();
elements.forEach(el => fragment.appendChild(el));
svg.appendChild(fragment);
// 避免
elements.forEach(el => svg.appendChild(el));function animate() {
// 更新动画
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);滤镜效果计算密集,应谨慎使用:
<!-- 避免多个小路径 -->
<path d="M10,10 L20,10"/>
<path d="M20,10 L20,20"/>
<!-- 使用单个路径 -->
<path d="M10,10 L20,10 L20,20"/><g stroke="black" fill="red">
<rect x="10" y="10" width="50" height="50"/>
<circle cx="100" cy="100" r="30"/>
</g>// 好
const element = document.getElementById('myElement');
for (let i = 0; i < 1000; i++) {
element.setAttribute('x', i);
}
// 避免
for (let i = 0; i < 1000; i++) {
document.getElementById('myElement').setAttribute('x', i);
}CSS 动画通常比 SMIL 和 JavaScript 动画性能更好:
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.element {
animation: rotate 2s linear infinite;
}.animated-element {
will-change: transform;
}避免在动画中读取会触发布局的属性:
// 避免
function animate() {
const width = element.getBoundingClientRect().width;
element.style.width = width + 1 + 'px';
requestAnimationFrame(animate);
}
// 好
let width = 100;
function animate() {
width++;
element.style.width = width + 'px';
requestAnimationFrame(animate);
}