Unused SVG defs Cleanup: What Nothing References
A <defs> block holds the parts of an illustration that are not drawn where
they are defined: gradients, clip paths, masks, filters, symbols, markers, patterns. They take space
and they draw nothing, which makes them the obvious thing to delete and the easiest thing to delete
wrongly. On a 3,540-byte drawing, 22 definitions took 2,419 bytes — 68% of the file —
and ten of them, 1,185 bytes, were referenced by nothing at all. Finding those ten is where
the scanners disagree: a url(#…) search called 18 definitions unused, and eight of them
were load-bearing, including a 73-byte gradient whose removal changed
8,868 pixels — 8% of the canvas.
The file is small on purpose, so every number can be checked: one 260 × 110 illustration, 22 definitions, 23 ids, rendered at 520 px after each deletion. The ground truth is a render, not a scanner's opinion — remove a definition, draw the file again, count the pixels that moved. A definition whose removal changes nothing is an orphan; one whose removal changes something is needed, whatever a search says.

Ground truth is a deletion test
Twenty-two deletions, one at a time, each followed by a 520 × 220 render and a diff against
the full file. Eleven changed nothing at all — ten definitions nothing reaches, plus the title that
is held by aria-labelledby. The other eleven changed between 156 and 8,868
pixels, and the order is not the one you would guess from the markup: the two smallest are a clip
path that cuts one corner (187 px) and an arrowhead (156 px), and the largest is a gradient that
fills the main badge.
| id | Kind | Bytes | px if deleted | Verdict |
|---|---|---|---|---|
clipAttr | clipPath | 68 | 187 | needed |
clipCss | clipPath | 79 | 2,560 | needed |
filterBlur | filter | 69 | 4,209 | needed |
gradA | linearGradient | 73 | 8,868 | needed |
gradBase | linearGradient | 153 | 8,868 | needed |
gradCss | radialGradient | 124 | 484 | needed |
markerEnd | marker | 176 | 156 | needed |
maskA | mask | 79 | 3,600 | needed |
patternA | pattern | 170 | 3,200 | needed |
symA | symbol | 94 | 544 | needed |
symB | symbol | 93 | 844 | needed |
ace | linearGradient | 148 | zero | orphan |
clipDead | clipPath | 77 | zero | orphan |
filterDead | filter | 67 | zero | orphan |
grad | radialGradient | 121 | zero | orphan |
gradDeadChild | linearGradient | 87 | zero | orphan |
gradDeadParent | linearGradient | 159 | zero | orphan |
gradOrphan | linearGradient | 155 | zero | orphan |
markerDead | marker | 148 | zero | orphan |
patternDead | pattern | 131 | zero | orphan |
symDead | symbol | 92 | zero | orphan |
ttl | title | 56 | zero | kept: aria |
Ten orphans, 1,185 bytes, a third of the file. Deleting all ten at once changes zero pixels — that is the whole prize, and it is available without touching the drawing. The rest of this page is about why five different ways of looking for those ten produce five different answers.
Five scanners, one file, five verdicts
Each scanner is a rule for "what counts as a reference", applied to the same file. The verdict column is not how many it found, it is how many of the definitions it called unused would actually have mattered — the number of mistakes the scanner would have baked into a build.
| Scanner | Calls unused | Of those, matter | Would free | First thing it misses |
|---|---|---|---|---|
substring #id | 8 | 1 | 813 B | keeps 428 dead bytes, drops the accessible name |
url(#…) only | 18 | 8 | 1,926 B | inherited gradients, <use> targets |
+ href="#…" | 14 | 5 | 1,427 B | everything referenced from CSS |
+ <style> block | 10 | 1 | 1,082 B | aria and SMIL references |
| + aria, sync base, reachability | 10 | 0 | 1,185 B | nothing at this size |
The ladder is monotone in one direction only: each added channel removes a class of mistake, and
nothing gets worse. A url(#…) search marks 18 of 22 definitions unused and gets eight
of them wrong. Adding href targets takes the errors from eight to five. Adding the
stylesheet takes them to one. The last step, reachability, takes it to zero — and at that point the
ten remaining verdicts are exactly the ten deletions that changed no pixels.
The 73-byte gradient that fills half the picture
gradA has no stops of its own. It inherits them from gradBase through
href="#gradBase", and the badge rectangle fills with url(#gradA). Delete
the child and the fill has no target; delete the parent and the child has nothing to inherit, which
in Chrome means the gradient paints nothing at all rather than falling back to black. Either
deletion changes 8,868 pixels and takes the drawing from 18,789 units of ink to
11,842 — 37% of the picture, gone, for 73 bytes of markup.
A url(#…) search misses both, for two different reasons: gradA is
referenced from a stylesheet rather than from an attribute, and gradBase is referenced
only by another definition. That is the shape of the problem.
Definitions reference definitions constantly — a gradient inherits stops from a gradient, a pattern
inherits content from a pattern, a filter chain reuses a primitive — and a scanner that only looks at
the drawing sees a family of definitions pointing at each other and has no way to tell which end of
the chain anything actually uses.
CSS is a reference channel too
Three definitions in the file are reachable only through the <style> block:
gradCss fills a dot, filterBlur softens a rectangle, and
clipCss clips another. Their deletions changed 484, 4,209 and 2,560 pixels. The clip
case is worth a second look: removing it increased the ink from 18,789 to 21,058,
because deleting a clip path reveals what it was hiding. A cleanup that only checks "did the file
get smaller" will never notice that its renders got heavier.
This is also the channel that breaks an otherwise reliable workflow, because the CSS can live outside the file: an inlined SVG can be filled by a stylesheet elsewhere on the page, and no scan of the file can see it. The fix is not a better scanner but a render of the page the SVG is inlined into.
Reachability, not "the string appears somewhere"
A substring search is the fastest thing to write and it fails in both directions. It fails
upstream because #gradBase appears inside
href="#gradBase" — a definition pointing at a definition — so a grep cannot tell a live
chain from a dead one. And it fails downstream on two ids in this file. One is ace, a
gradient whose id is also a valid hex colour: the drawing fills a rectangle with
"#ace", and a search for #ace finds it, so the gradient is kept forever.
The other is grad, whose id is a prefix of #gradA and
#gradBase: same mistake, no colour involved. Together the two baits are 269 bytes that
a grep will never free, and the two members of the dead chain are another 246.
Reachability fixes both directions. Start from what the drawing and the stylesheet ask for — the
seeds — then follow references outward from the definitions those seeds reach. gradA is
a seed through CSS, so gradBase is live. gradDeadChild is not a seed, so
its href does not save gradDeadParent. And ace and
grad never enter the live set, because a colour literal and a prefix are not
references.
Two definitions that never paint and must stay
The first is ttl, a <title> inside the block, referenced by
aria-labelledby on the root element. Deleting it changes zero pixels and no scan based
on url() or href objects. It is the accessible name of the image, and the
sentence an assistant reads when it describes the file. Every scanner on the previous table except
the last one deletes it.
The second is not in the table because it is not a definition: an id the page's own JavaScript
looks up. Inlining an SVG turns its ids into document ids, and
document.getElementById('gradA') — for a hover state, an animation, a theme switch — is
a reference that lives outside the file. Static analysis of an inlined SVG is only valid alongside a
search of the scripts that touch it.
The scanner, in three functions
First, collect the references and keep the channels apart, because the whole point of the table above is that a scanner which knows one channel reports the others as unused.
// Every channel that can point at an id, kept apart because a scanner that knows
// only one of them reports the others as unused.
function referencesIn(svg) {
const refs = new Map();
const add = (id, ch) => {
if (!id) return;
if (!refs.has(id)) refs.set(id, new Set());
refs.get(id).add(ch);
};
const cssBlocks = [...svg.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)].map((m) => m[1]).join('\n');
const markup = svg.replace(/<style[^>]*>[\s\S]*?<\/style>/g, '');
const url = /url\(\s*['"]?#([A-Za-z_][\w:.-]*)/g;
for (const m of markup.matchAll(url)) add(m[1], 'attribute url()');
for (const m of markup.matchAll(/\b(?:xlink:)?href\s*=\s*["']#([A-Za-z_][\w:.-]*)/g)) add(m[1], 'href');
const cssUrl = /url\(\s*['"]?#([A-Za-z_][\w:.-]*)/g;
for (const m of cssBlocks.matchAll(cssUrl)) add(m[1], 'stylesheet url()');
for (const m of cssBlocks.matchAll(/(?:^|[},\s])#([A-Za-z_][\w-]*)\s*(?=[,{])/g)) add(m[1], 'stylesheet selector');
for (const m of markup.matchAll(/aria-(?:labelledby|describedby)\s*=\s*["']([^"']+)/g)) {
for (const id of m[1].split(/\s+/)) add(id, 'aria');
}
for (const m of markup.matchAll(/\b(?:begin|end)\s*=\s*["']([^"']+)/g)) {
for (const part of m[1].split(';')) {
const t = /^\s*([A-Za-z_][\w:.-]*?)\s*\./.exec(part);
if (t && t[1] !== 'id') add(t[1], 'sync base');
}
}
return refs;
}
Second, reachability from the seeds. This is the function that decides that a definition only another dead definition points at is still dead.
// Reachability, not substring presence: start at what the drawing asks for, then
// follow the definitions those point at. A definition that only another dead
// definition points at stays dead.
function targetsOf(attrs) {
const out = new Set();
for (const m of String(attrs).matchAll(/url\(\s*['"]?#([A-Za-z_][\w:.-]*)/g)) out.add(m[1]);
for (const m of String(attrs).matchAll(/(?:xlink:)?href\s*=\s*["']#([A-Za-z_][\w:.-]*)/g)) out.add(m[1]);
for (const m of String(attrs).matchAll(/aria-(?:labelledby|describedby)\s*=\s*["']([^"']+)/g)) {
for (const id of m[1].split(/\s+/)) out.add(id);
}
return out;
}
function reachableIds(svg) {
const start = svg.search(/<defs[\s>]/);
const end = svg.search(/<\/defs>/);
const inDefs = (i) => start >= 0 && i >= start && i <= end;
const edges = new Map();
const seeds = new Set();
const tagRe = /<([A-Za-z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*?)\/?>/g;
for (const m of svg.matchAll(tagRe)) {
const idm = /\sid\s*=\s*["']([^"']+)/.exec(m[2]);
const id = idm ? idm[1] : null;
const targets = targetsOf(m[2]);
if (id) edges.set(id, targets);
if (!inDefs(m.index)) for (const t of targets) seeds.add(t);
}
// a stylesheet lives outside defs and can point at anything
for (const m of svg.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)) {
for (const t of targetsOf(m[1])) seeds.add(t);
}
const seen = new Set();
const queue = [...seeds];
while (queue.length) {
const id = queue.pop();
if (seen.has(id)) continue;
seen.add(id);
for (const t of edges.get(id) || []) queue.push(t);
}
return seen;
}
Third, the verdict and the removal, which works on offsets rather than on a rebuilt regular
expression so that ids containing ., + or ( do not turn into
a broken pattern. It also reports the two traps, which is what makes a grep-based cleanup
auditable.
// The verdict, plus the two ways a substring grep gets it wrong. Removal works on
// offsets, not on a rebuilt regular expression, so ids with regex characters are safe.
function unusedDefs(svg) {
const start = svg.search(/<defs[\s>]/);
const end = svg.search(/<\/defs>/);
if (start < 0 || end < 0) return { unused: [], bytes: 0, fileBytes: svg.length, traps: [] };
const live = reachableIds(svg);
const unused = [];
const tagRe = /<([A-Za-z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
for (const m of svg.matchAll(tagRe)) {
if (m.index < start || m.index > end) continue;
const idm = /\sid\s*=\s*["']([^"']+)/.exec(m[2]);
if (!idm || live.has(idm[1])) continue;
let stop = m.index + m[0].length;
if (!m[3]) {
const closer = svg.indexOf('</' + m[1] + '>', stop);
if (closer >= 0) stop = closer + m[1].length + 3;
}
unused.push({ id: idm[1], tag: m[1], bytes: stop - m.index, start: m.index, end: stop });
}
// what a grep for "#id" would have claimed, and why it is wrong
const traps = unused.filter((d) => svg.includes('#' + d.id)).map((d) => ({
id: d.id,
hexColour: /^[0-9a-f]{3,8}$/i.test(d.id) && svg.includes('"#' + d.id + '"'),
prefixOfAnotherId: new RegExp('#' + d.id + '[A-Za-z0-9_-]').test(svg),
}));
return { unused, bytes: unused.reduce((n, d) => n + d.bytes, 0), fileBytes: svg.length, traps };
}
// Remove them in one pass, last offset first. A second run finds nothing to do.
function stripUnusedDefs(svg) {
const { unused } = unusedDefs(svg);
let out = svg;
for (const d of unused.slice().sort((x, y) => y.start - x.start)) {
out = out.slice(0, d.start) + out.slice(d.end);
}
return out;
}
Running it on the measured file returns exactly the ten orphans, 1,185 bytes, and a
second run returns nothing — the same definition of done as any other cleanup step. The traps list
comes back with ace flagged as a hex colour and grad flagged as a prefix,
which is the difference between a scanner and a search.
The checklist
- Inventory the block. Count the definitions and their bytes before deleting anything; on this file it was 68% of the size, which is the reason to care.
- Scan every channel. Attributes,
href, stylesheet,aria-*, SMIL sync bases. - Walk reachability from the drawing, not from "does this id appear".
- Keep
<title>and<desc>even when nothing points at them with aurl(). - Render before and after at the size you ship, and count ink as well as differing pixels — a deleted clip path can add paint.
- Re-run the scan on the result and confirm it is empty. A stripper that leaves an orphan behind on the second pass is not idempotent, and a build step will find that out for you.
Both of the other cleanup passes on this site follow the same shape. The invisible elements pass asks whether a shape draws at all (see removing invisible elements from an SVG); this one asks whether anything reaches a definition; and the metadata pass asks whether a byte is editor state, which is the third article in the set. Do them in that order for a quick win, and in the reverse order when you want the smallest diff to review.
One number to keep: on the ten-file audit behind why an SVG file gets large, the same scene arrived in 453 bytes and in 92,048 bytes, and unused definitions were part of the spread. A definition nothing reaches is the cleanest byte in the file to remove, because it is the only kind of removal that has a proof.
Related SVG Workflows
A dead definition costs bytes and nothing else; the next two articles cover the parts of a cleanup that can cost pixels.
- Removing invisible elements from an SVG — 24 candidates, nine of them actually free, measured at two sizes.
- Remove SVG Metadata — the other free half: editor state, namespaces and unreferenced ids.
- Why Is My SVG File So Large? — ten files of the same drawing, split by byte category.
- Best Free SVG Optimizer Tools — which of them remove unused defs, and which only remove whitespace.
- SVG Namespace Security — why an id that resolves to the wrong thing is worse than a dangling one.
- Figma SVG Clean Code — what Figma puts in a defs block that nothing uses.
- SVG Editor — open the file, click the orphan, see what it was supposed to do.
Try These Free Online Tools
No download required — convert, compress & optimize SVGs right in your browser



