Inlining the same SVG many times breaks url(#id) in Firefox
If you inject the same SVG icon into a page several times, every copy declares the same id values, and a reference such as fill="url(#grad)" resolves to the first element in the document with that id, not to the one inside its own copy. When that first copy is hidden, the others can render with missing gradients, masks or clip paths, which a teammate saw in Firefox. The fix is to give each injected copy its own ids.
Where the broken icons came from
This came up on one member site in a group of nonprofit membership sites that share a Drupal distribution. The theme builds its icons with webpack: require.context pulls in a folder of SVG files as strings, and jQuery inserts a copy of the right string wherever an icon is needed. It's a common pattern because inline SVG can be styled with CSS and needs no extra requests.
Most icons were fine. The broken ones were the icons that used a gradient, a mask or a clip path, and they broke on pages where the same icon appeared more than once. Cards were the giveaway: a card with a hover-state icon, hidden until hover, was enough to break the other visible copies of that icon.
Why duplicate ids break url(#id) references
An SVG gradient is defined once, inside <defs>, with an id, and shapes refer to it:
<svg viewBox="0 0 24 24">
<defs>
<linearGradient id="fade">
<stop offset="0" stop-color="#fff"/>
<stop offset="1" stop-color="#0a6"/>
</linearGradient>
</defs>
<circle cx="12" cy="12" r="10" fill="url(#fade)"/>
</svg>
Once that markup is inline, the id belongs to the HTML document, not to the icon. Ids are meant to be unique per document; paste the icon in five times and you have five elements called fade. A reference like url(#fade) or href="#fade" is looked up in the document, and the lookup returns the first match. Every copy of the icon ends up pointing at the gradient in the first copy.
That is harmless while the first copy is visible. When it sits in a hidden subtree (a display: none hover icon, a closed menu, an inactive tab), the gradient it holds is not rendered, and in Firefox the other copies that point at it lost their fills too. Whether a given browser paints a gradient that lives in a hidden subtree has varied between browsers and versions, so even where it looks fine today you are relying on behaviour you don't control.
How the team gave each copy unique ids
The team's fix keeps the inline-injection approach and makes every injected copy unique. It works in two steps:
- At load time, each SVG string is turned into a template. Every declared
idgets a placeholder suffix, and so does every#idreference that matches one of those declared ids. Matching only declared ids matters: it leaves colour values such as#fffalone. - On each injection, the placeholder is replaced with a counter, so the first copy gets
fade-1, the secondfade-2, and each copy's references point at its own definitions.
Icons without any ids skip all of this and are injected as before. Here's a fresh, minimal version of the idea:
const SLOT = '__copy__';
let copies = 0;
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Mark every declared id, and every #id reference to it, with SLOT.
function toTemplate(svg) {
const ids = [...svg.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]);
if (ids.length === 0) return null;
return ids.reduce((out, id) => {
const name = escape(id);
return out
.replace(new RegExp(`(\\sid=")${name}"`, 'g'), `$1${id}${SLOT}"`)
.replace(new RegExp(`#${name}(?![\\w-])`, 'g'), `#${id}${SLOT}`);
}, svg);
}
// Return markup for one copy, with ids unique to that copy.
function instantiate(svg, template) {
if (!template) return svg;
copies += 1;
return template.split(SLOT).join(`-${copies}`);
}
const svg = '<svg><defs><linearGradient id="fade"><stop stop-color="#fff"/></linearGradient></defs><circle fill="url(#fade)"/></svg>';
const template = toTemplate(svg);
console.log(instantiate(svg, template));
console.log(instantiate(svg, template));
Running it prints two copies, one using fade-1 and one using fade-2, with #fff untouched. The negative lookahead stops an id like a from also rewriting a reference to a-b. Building the template once per file, rather than on every injection, keeps the per-icon cost to a single string split.
String rewriting has limits. It assumes double-quoted id attributes, and it doesn't parse <style> blocks inside the SVG that select by id. For icons that come out of a design tool with those features, parsing the string with DOMParser and walking the attributes is sturdier, at the cost of more code.
Other ways to avoid duplicate SVG ids
Unique ids per copy is the smallest change when icons are already injected as strings. Other approaches avoid the problem rather than fix it:
- An SVG sprite with
<use>. Define each icon once in a sprite and reference it with<use href="#icon-name">. The definitions exist once, so there is nothing to duplicate, though styling the inside of a<use>copy is more limited. - SVGO's
prefixIdsplugin. It prefixes ids per file at build time, which stops two different icons from colliding. It does not help when the same file is inserted many times, because every copy gets the same prefix. - CSS masks. For single-colour icons,
mask-imagewith the SVG as a URL andbackground-colorfor the colour needs no inline markup and no ids at all. - Removing the ids. Sometimes a gradient or mask in an icon is decoration nobody asked for, and flattening it in the source file is the cleanest fix.
What I like about the team's approach is that it's local: one function at the point of injection, no change to how icons are authored or how the theme uses them, and icons without ids are untouched.
Key takeaways
- Inline SVG ids belong to the whole HTML document, so injecting the same icon several times creates duplicate ids.
- A
url(#id)orhref="#id"reference resolves to the first element with that id in the document, not to the one inside its own SVG. - When the first copy is hidden, as with a hover-state icon, other copies can lose their gradients, masks or clip paths, as happened in Firefox here.
- Rewriting each declared id and its matching references with a per-copy suffix fixes it without touching colour values such as
#fff. - SVGO's
prefixIdsprevents collisions between different files but not between copies of the same file.