乐闻世界logo
搜索文章和话题

How to optimize SVG to improve performance

2月21日 15:21

SVG optimization is crucial for improving web page performance and user experience. Here are common SVG optimization techniques:

1. Remove Unnecessary Code

  • Delete metadata added by editors (like <title>Created with...</title>)
  • Remove comments and blank lines
  • Delete unused definitions and styles
  • Use tools like SVGO for automatic optimization

2. Simplify Paths

  • Use shorter path commands (like h instead of H)
  • Merge adjacent identical commands
  • Reduce decimal precision (e.g., 50.123456 to 50.12)
  • Use relative coordinates instead of absolute coordinates

3. Optimize Attributes

  • Remove default value attributes (e.g., fill="black" can be omitted)
  • Use shorthand attributes (e.g., stroke instead of stroke-color)
  • Merge identical styles into class or <style> tags

4. Compress SVG Files

  • Use gzip compression (server configuration)
  • Optimize with tools like SVGO
  • Remove DOCTYPE declaration (doesn't affect rendering)

5. Use SVG Sprite

  • Merge multiple icons into one SVG file
  • Use <symbol> and <use> elements to reuse graphics
  • Reduce HTTP requests

Example:

svg
<svg style="display: none;"> <symbol id="icon-home" viewBox="0 0 24 24"> <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/> </symbol> <symbol id="icon-user" viewBox="0 0 24 24"> <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/> </symbol> </svg> <!-- Use icons --> <svg><use href="#icon-home"/></svg> <svg><use href="#icon-user"/></svg>

6. Inline Critical SVGs

  • Inline critical SVGs for first-screen rendering into HTML
  • Avoid additional HTTP requests
  • Non-critical SVGs can be lazy-loaded

7. Use viewBox Instead of width/height

  • Use viewBox for responsive scaling
  • Control display size via CSS
  • Improve flexibility

8. Reduce Element Count

  • Merge paths that can be merged
  • Use <g> for grouping instead of multiple independent elements
  • Avoid unnecessary nesting

9. Optimize Animation Performance

  • Prioritize CSS animations (GPU accelerated)
  • Use transform and opacity properties
  • Avoid animating width, height, left, top properties

10. Recommended Tools

  • SVGO: Powerful SVG optimization tool
  • SVGOMG: Online SVG optimization tool
  • Iconfont: Icon font and SVG management
  • Figma/Sketch: Optimize SVG when exporting

Optimization Example:

bash
# Optimize with SVGO npx svgo input.svg -o output.svg # Batch optimize npx svgo -f ./icons -o ./optimized

Performance Testing:

  • Use Lighthouse to test page performance
  • Check SVG file size and load time
  • Monitor rendering performance
标签:SVG