Often, when “unused” comes up in dialog concerning CSS, it’s about eradicating chunks of CSS that aren’t utilized in your web site or, not less than, the types not at the moment in use on a particular web page. The minimal quantity of CSS is greatest! I’ve written about how that is a tough downside up to now. In JavaScript-land, the equal is tree shaking (eradicating unusued JavaScript).
However what concerning the different approach round, detecting lessons in HTML that aren’t utilized in your CSS? In the event you knew this for certain, you can clear up your markup, eradicating lessons that don’t do something.
I noticed Robert Kieffer put up a Gist the opposite day with an fascinating answer. The thought is to load up doc.styleSheets and discover all the principles (those which are lessons). Then, use a MutationObserver to observe the DOM for all HTML, and examine the classList of every node to see if it matches any from any stylesheet. If the HTML has a category not present in a stylesheet, report it.
I gave it a fast whirl and acquired it working and accurately reporting unused lessons:
Your mileage might fluctuate. For one factor, this script is about up as an ES Module. Which means if you happen to simply import it and run it on a daily ol’ HTML doc, it gained’t discover something as a result of your <script kind=”module”> is deferred and the MutationObserver gained’t choose something up. I simply un-moduled it and put it within the <head> to make my demo work.
I Netlify Dropped the web site on-line in case you wanna dig into it and test it out. I might have used CodePen, however CodePen doesn’t hyperlink up your types as <hyperlink>ed stylesheets (by default, however you can use exterior assets to do this). I simply thought it could be extra clear as a deployed web site.
Cautious now.
Identical to unused CSS is a tough downside due to how exhausting it’s to know for certain know if a ruleset is unused, this strategy could also be an even more durable downside. For one factor, lessons may be used as a JavaScript hook for issues. Types may get injected onto the web page in <type> blocks, which this script wouldn’t examine. Heck, you may need integration exams that run in CI that use lessons to do testing-related issues.
I’d say this type of factor is a useful gizmo for havin’ a looksie at lessons that you’ve got a hunch may be unused. However I wouldn’t say there’s a permission slip to run this factor after which yank out each reported class with out additional investigation.
The put up Detect Unused Lessons in… HTML appeared first on CSS-Methods.
You’ll be able to assist CSS-Methods by being an MVP Supporter.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!