Updated November 24, 2026  ·  10 min read  ·  SVGVector

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.

Left: 2,419 of 3,540 bytes sit in the defs block, and 1,185 of those bytes belong to ten definitions nothing reaches. Right: five scanners and how many of the definitions they call unused actually matter, from eight for a url() scan down to zero for a reachability walk.
One 3,540-byte illustration with 22 definitions. The left panel is where the bytes are; the right panel is what each kind of reference scan would have deleted.

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.

idKindBytespx if deletedVerdict
clipAttrclipPath68187needed
clipCssclipPath792,560needed
filterBlurfilter694,209needed
gradAlinearGradient738,868needed
gradBaselinearGradient1538,868needed
gradCssradialGradient124484needed
markerEndmarker176156needed
maskAmask793,600needed
patternApattern1703,200needed
symAsymbol94544needed
symBsymbol93844needed
acelinearGradient148zeroorphan
clipDeadclipPath77zeroorphan
filterDeadfilter67zeroorphan
gradradialGradient121zeroorphan
gradDeadChildlinearGradient87zeroorphan
gradDeadParentlinearGradient159zeroorphan
gradOrphanlinearGradient155zeroorphan
markerDeadmarker148zeroorphan
patternDeadpattern131zeroorphan
symDeadsymbol92zeroorphan
ttltitle56zerokept: 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.

ScannerCalls unusedOf those, matterWould freeFirst thing it misses
substring #id81813 Bkeeps 428 dead bytes, drops the accessible name
url(#…) only1881,926 Binherited gradients, <use> targets
+ href="#…"1451,427 Beverything referenced from CSS
+ <style> block1011,082 Baria and SMIL references
+ aria, sync base, reachability1001,185 Bnothing 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

  1. 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.
  2. Scan every channel. Attributes, href, stylesheet, aria-*, SMIL sync bases.
  3. Walk reachability from the drawing, not from "does this id appear".
  4. Keep <title> and <desc> even when nothing points at them with a url().
  5. Render before and after at the size you ship, and count ink as well as differing pixels — a deleted clip path can add paint.
  6. 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.

Try These Free Online Tools

No download required — convert, compress & optimize SVGs right in your browser

Inventory

SVG Validator

Count definitions and check every reference resolves.

Open validator
Strip

SVG Optimiser

Remove unused defs and metadata with a byte count.

Open optimiser
Inspect

SVG to Code

See the defs block as text, ids and all.

Read the code
Verify

SVG to PNG

Re-render after the cleanup and diff at ship size.

Render it
Edit

SVG Editor

Open the file and click the definition before deleting it.

Open editor
Crop

Crop, Flip, Rotate

Change the viewBox and see what was only clipped.

Open tool