← Back to HTML & CSS, page 9

html-css-0176 · Hard senior

How would you audit a stylesheet for unused rules and risky patterns, and what are the limits of a script?

Measure size, rule counts, unused rules, strong selectors and !important with the coverage panel and a CSSOM script. The output is a list of candidates only, because rules can be used in other states, pages or dynamic cases, and cross-origin sheets cannot be read.

Full answer

An audit gives numbers and a list of problems. The sources are the browser tools and a small script over the CSS Object Model (CSSOM).

What to look for:

  • Size and count: bytes sent, number of rules and number of selectors.
  • Unused rules: selectors that match nothing on the pages you checked. The coverage panel in the browser tools shows the used and unused bytes for a page load.
  • Duplicates and overrides: the same property set again and again for one selector, or by many selectors.
  • Strong selectors: ids, deep descendant chains and many classes, which cause specificity fights.
  • !important: the number of uses, and where they are.
  • Inline styles in the HTML, and vendor prefixes that are no longer needed.

A script can read document.styleSheets, loop over cssRules and test each selector with document.querySelector(). Treat the output as a list of candidates, not as a list of things to delete.

Limits:

  • A selector that matches nothing now may match after a click, in another state, on another page, or for another user. State pseudo-classes such as :hover cannot be tested by querySelector, so strip them or skip them.
  • The script sees one page. Combine results from many pages, and from the real site traffic if possible.
  • Cross-origin style sheets cannot be read, because the browser blocks access to their rules.
  • Rules in @media and @layer blocks need a recursive walk.
  • Dynamic class names, built by JavaScript, will look unused.

Before deleting anything, check the candidate rules in a test build with visual tests.

The report finds five rules from the style element. It lists .ghost, #nope and .also-ghost as unused. It does not list a:hover, because the state is removed first. It counts one !important. These are the candidates to look at, and a person must still decide.

The page is read once. Run the same check on many pages before trusting the list.

html
<style>
  .used { color: rgb(10, 20, 30); }
  .ghost { color: red !important; }
  #nope { margin: 0; }
  a:hover { text-decoration: underline; }
  @media (min-width: 400px) { .also-ghost { padding: 1px; } }
</style>
<p class="used">Used</p><a href="#">Link</a>
<script>
  const report = { rules: 0, unused: [], important: 0 };
  const stateless = s => s.replace(/:(hover|focus|active|visited|focus-visible|focus-within)\b/g, "");
  function walk(rules) {
    for (const rule of rules) {
      if (rule.cssRules && !rule.selectorText) { walk(rule.cssRules); continue; }
      if (!rule.selectorText) continue;
      report.rules++;
      if (!document.querySelector(stateless(rule.selectorText))) report.unused.push(rule.selectorText);
      for (const p of rule.style) if (rule.style.getPropertyPriority(p) === "important") report.important++;
    }
  }
  for (const sheet of [...document.styleSheets]) { try { walk(sheet.cssRules); } catch (e) {} }
  window.report = report;
</script>

The script was run on this one test page in Chrome 156. Real sites need many pages and states. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Use coverage and a CSSOM script.
  • Measure size, unused rules, specificity and !important.
  • Strip state pseudo-classes before testing selectors.
  • Combine results from many pages and states.
  • Verify before deleting.

Common mistakes

  • Deleting every rule that a script reports as unused.
  • Testing only one page and one state.
  • Forgetting that dynamic class names look unused.

Follow-ups

  • Why can :hover rules not be tested with querySelector?
  • Why can a script not read some stylesheets?

Tips

  • List what you measure, then the tools, then the limits.
  • Say that a script gives candidates, and humans check them.