{T}

性能优化

SVG 性能优化对于创建流畅、响应迅速的 Web 应用至关重要。本章节介绍各种优化技巧和最佳实践。

文件大小优化

使用 SVGOMG 优化

SVGOMG 是一个在线 SVG 优化工具,可以:

  • 移除不必要的元数据
  • 简化路径数据
  • 移除注释和空白
  • 合并元素

手动优化技巧

  1. 移除不必要的属性
xml
<!-- 优化前 -->
<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>
  1. 使用相对坐标

相对坐标通常比绝对坐标更紧凑。

  1. 复用元素

使用 <defs><use> 复用重复元素。


渲染性能优化

减少重绘和重排

  1. 使用 CSS transform 而不是修改坐标
css
/* 好 */
.element {
  transform: translate(100px, 100px);
}

/* 避免 */
.element {
  left: 100px;
  top: 100px;
}
  1. 批量修改 DOM
javascript
// 好
const fragment = document.createDocumentFragment();
elements.forEach(el => fragment.appendChild(el));
svg.appendChild(fragment);

// 避免
elements.forEach(el => svg.appendChild(el));

使用 requestAnimationFrame

javascript
function animate() {
  // 更新动画
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

合理使用滤镜

滤镜效果计算密集,应谨慎使用:

  • 避免对大量元素应用滤镜
  • 使用简单的滤镜效果
  • 考虑使用 CSS 滤镜替代

DOM 操作优化

减少 DOM 元素数量

  1. 合并路径
xml
<!-- 避免多个小路径 -->
<path d="M10,10 L20,10"/>
<path d="M20,10 L20,20"/>

<!-- 使用单个路径 -->
<path d="M10,10 L20,10 L20,20"/>
  1. 使用 group 元素
xml
<g stroke="black" fill="red">
  <rect x="10" y="10" width="50" height="50"/>
  <circle cx="100" cy="100" r="30"/>
</g>

缓存 DOM 查询

javascript
// 好
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 动画

CSS 动画通常比 SMIL 和 JavaScript 动画性能更好:

css
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.element {
  animation: rotate 2s linear infinite;
}

使用 will-change

css
.animated-element {
  will-change: transform;
}

避免布局抖动

避免在动画中读取会触发布局的属性:

javascript
// 避免
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);
}

工具与资源

优化工具

  • SVGOMG: 在线 SVG 优化工具
  • SVGO: Node.js SVG 优化工具
  • SVG Cleaner: 桌面 SVG 优化工具

性能分析工具

  • Chrome DevTools: Performance 面板
  • Firefox Developer Tools: Performance 工具
  • Lighthouse: Web 性能审计工具

参考资源