How to Cache-Bust External SVG Sprite Sheets

Managing browser cache for external SVG sprite sheets is essential to ensure that design updates and new icons render immediately without requiring users to manually clear their cache. This article explains how to apply cache-busting query strings or file hashes to external SVG sprites using the SVG <use> tag, highlights browser behavior regarding query parameters in fragment identifiers, and outlines best practices for implementation.

Applying Query Strings to the SVG <use> Element

External SVG icons are typically loaded using the HTML <svg> element referencing an internal symbol ID via the <use> tag. You can append a query string parameter directly to the file path before the hash fragment identifier:

<svg class="icon">
  <use href="/assets/icons/sprite.svg?v=1.0.4#user-profile"></use>
</svg>

For legacy browser support, the xlink:href attribute can be used alongside or instead of href:

<svg class="icon">
  <use xlink:href="/assets/icons/sprite.svg?v=1.0.4#user-profile"></use>
</svg>

When the version query parameter (e.g., ?v=1.0.4 or ?t=1698745600) changes, the browser treats the reference as a new resource request, bypassing the cached copy.

Automated Query String Integration

To avoid manual version updates, integrate query parameters into your server-side templates or build pipelines:

Dynamic Server-Side Templates

Append a deployment timestamp or application version variable directly in your templates (such as Blade, Liquid, or Jinja):

<!-- Example in a templating engine -->
<svg>
  <use href="/assets/sprite.svg?v={{ app.version }}#search"></use>
</svg>

JavaScript Helper Functions

If icons are rendered dynamically on the client side, construct the path using an environment variable or timestamp:

const SPRITE_VERSION = "2.1.0";

function renderIcon(iconName) {
  return `
    <svg class="icon">
      <use href="/assets/sprite.svg?v=${SPRITE_VERSION}#${iconName}"></use>
    </svg>
  `;
}

Query Strings vs. Filename Hashing

While query strings (sprite.svg?v=123#icon) work in modern browsers, filename-based cache busting (sprite.123.svg#icon) is the industry standard for several technical reasons:

  1. Proxy and CDN Reliability: Some proxy servers, CDNs, and intermediate caches ignore query strings by default and serve stale assets regardless of the parameter.
  2. Fragment Identifier Parsing: Older browser versions occasionally fail to separate the query string from the fragment identifier, resulting in a failed asset lookup.
  3. Build Tool Alignment: Bundlers like Webpack, Vite, and Rollup natively generate content-hashed filenames during asset optimization.

Example of Filename Hashing:

<svg class="icon">
  <use href="/assets/sprite.a8f9c2d.svg#settings"></use>
</svg>

Important Server Configuration Rules

Regardless of whether you use query strings or filename hashing, the web server must be properly configured: