Usually, when “unused” comes up in conversation regarding CSS, it’s about removing chunks of CSS that are not used in your site or, at least, the styles not currently in use on a specific page. The minimal amount of CSS is best! I’ve written about how this is a hard problem in the past. In JavaScript-land, the equivalent is tree shaking (removing unusued JavaScript).
But what about the other way around, detecting classes in HTML that aren’t used in your CSS? If you knew this for sure, you could clean up your markup, removing classes that don’t do anything.
I saw Robert Kieffer post a Gist the other day with an interesting solution. The idea is to load up document.styleSheets
and find all the rules (the ones that are classes). Then, use a MutationObserver
to watch the DOM for all HTML, and check the classList
of each node to see if it matches any from any stylesheet. If the HTML has a class not found in a stylesheet, report it.
I gave it a quick whirl and got it working and correctly reporting unused classes:
Your mileage may vary. For one thing, this script is set up as an ES Module. That means if you just import
it and run it on a regular ol’ HTML document, it won’t find anything because your <script type="module">
is deferred and the MutationObserver
won’t pick anything up. I just un-moduled it and put it in the <head>
to make my demo work.
I Netlify Dropped the site online in case you wanna dig into it and check it out. I would have used CodePen, but CodePen doesn’t link up your styles as <link>
ed stylesheets (by default, but you could use external resources to do that). I just thought it would be more clear as a deployed site.
Careful now.
Just like unused CSS is a hard problem because of how hard it is to know for sure know if a ruleset is unused, this approach may be an even harder problem. For one thing, classes might be used as a JavaScript hook for things. Styles might get injected onto the page in <style>
blocks, which this script wouldn’t check. Heck, you might have integration tests that run in CI that use classes to do testing-related things.
I’d say this kind of thing is a useful tool for havin’ a looksie at classes that you have a hunch might be unused. But I wouldn’t say there’s a permission slip to run this thing and then yank out every reported class without further investigation.
The post Detect Unused Classes in… HTML appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.
source https://css-tricks.com/detect-unused-classes-in-html/
No comments:
Post a Comment