Skip to content

SVG

Rule

There are several reasons for that :

  • No extra HTTP requests - When SVGs are included as separate files (using <img>, <object>, etc.), the browser makes additional HTTP requests to fetch them. Inlining eliminates these requests, improving page load performance.
  • Style control - Inlined SVGs become part of your DOM, allowing you to target and style SVG elements with CSS. You can change colors, strokes, and other properties dynamically.
  • JavaScript interaction - Direct DOM access means you can manipulate SVG elements with JavaScript, enabling animations and interactive features.
  • No cross-origin restrictions - Inlined SVGs avoid cross-origin issues that might occur with externally referenced SVGs.
  • Guaranteed availability - The SVG loads with the HTML, ensuring it's always available when needed without synchronization issues.
  • No caching issues - You don't need to worry about browser caching when updating the SVG; it changes whenever you update the HTML.
  • Compression efficiency - Modern web servers with gzip/brotli compression can efficiently compress HTML with inlined SVGs, often reducing the total size compared to separate files.

Examples

🚨 DON’T

<!-- External file reference - requires HTTP request -->
<img src="icons/chevron-down.svg" alt="Dropdown arrow" />

<!-- Object tag - also requires HTTP request -->
<object data="icons/user-profile.svg" type="image/svg+xml"></object>

<!-- CSS background-image - external request -->
<div class="icon" style="background-image: url('icons/search.svg');"></div>

<!-- Multiple instances of the same external SVG -->
<img src="icons/star.svg" alt="Rating star" />
<img src="icons/star.svg" alt="Rating star" />
<img src="icons/star.svg" alt="Rating star" />
<img src="icons/star.svg" alt="Rating star" />
<img src="icons/star.svg" alt="Rating star" />

<!-- SVG without proper attributes for styling/accessibility -->
<svg>
  <path
    d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"
  />
</svg>

✅ DO

<!-- Inline simple icons with proper attributes -->
<svg
  viewBox="0 0 24 24"
  width="20"
  height="20"
  fill="currentColor"
  aria-label="Dropdown arrow"
>
  <path d="M7 10l5 5 5-5z" />
</svg>

<!-- SVG with CSS custom properties for theming -->
<svg viewBox="0 0 24 24" width="24" height="24" class="user-icon">
  <path
    fill="var(--icon-color, #333)"
    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"
  />
</svg>

<!-- Optimized SVG with removed unnecessary attributes -->
<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
  <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
</svg>

Integration

Angular

React