SVG ファイルを最適化する方法
メタデータ、未使用の要素、冗長なデータを取り除いて SVG ファイルサイズを削減します。
问题
SVG ファイルに不要なデータが含まれており、サイズが肥大化してページの読み込みが遅くなっています。
前提条件
- SVG 構造の理解
- XML 最適化に関する知識
ステップ
-
1. Remove unnecessary metadata
SVG editors (Illustrator, Inkscape) embed metadata: editor info, layer names, comments, and unused definitions. Remove these to reduce size. Also remove the XML declaration and DOCTYPE if not needed, and the inkscape/sodipodi namespaces.
入力SVG with metadata输出metadata removed -
2. Simplify paths and shapes
Reduce path precision to fewer decimal places (typically 2-3 is sufficient for display). Convert shapes to paths where it reduces size. Merge overlapping paths. Remove invisible elements and unused gradients/filters. Round coordinates.
入力path: M 10.123456 20.789012 L...输出M 10.12 20.79 L... -
3. Minify and validate
Remove whitespace between tags, collapse attributes, and shorten IDs. Validate the optimized SVG renders identically to the original. Tools like SVGO automate all these optimizations safely. Compare file sizes before and after.
入力optimized SVG输出size reduced ~50-70%
期待される結果
元のファイルと同じように描画される、より小さい SVG ファイル。
よくあるエラー
- Optimized SVG renders differently
- Some optimizations (like removing gradients) change appearance. Use a conservative optimizer or disable specific plugins that cause issues.
- IDs referenced by JavaScript are removed
- Configure the optimizer to preserve IDs that are referenced by CSS or JavaScript. SVGO has a cleanupIDs plugin that can be configured with a preserve list.
トラブルシューティング指引
- If the SVG looks different after optimization, compare the original and optimized rendering.
- Keep IDs used by animations or scripts. Configure the optimizer to preserve them.
セキュリティ上の制限
- SVG can contain scripts and external references. Sanitize SVGs from untrusted sources before embedding.
- All optimization is local.