How do you get rid of unused CSS code? Part 1

The author of the article, the first part of the translation of which we are publishing today, would like readers to know in advance that getting rid of unnecessary CSS is a difficult task. If you read this in the hope of finding a tool, running it, you can find out exactly which CSS code can be safely removed from your project, then ... There are similar tools, but they must be used very carefully, since none of them not able to give a decent answer to the question of unused CSS.







It’s easy to understand that any web developer would like to take some kind of utility, run it, and remove the unnecessary CSS that it reports. A couple of minutes - and the site is accelerated. But not so simple. The author of this material believes that such a tool should be treated with healthy skepticism. None of them lie to the developer. These tools usually simply do not have enough information to enable them to produce results that can be unconditionally trusted. But this does not mean that such tools cannot be used. This does not mean that you cannot get rid of unused CSS in any way. We discuss this.



Read the second part



Why get rid of unused CSS?



I believe that the main reason someone might need to get rid of unused CSS can be described using the following example. Suppose you use a CSS framework (like Bootstrap) and all of the CSS code for that framework gets into your project. But in reality, only a small part of such code is used in the project. How to get rid of all unnecessary?



I can feel the feelings of someone who is in a similar situation. CSS frameworks often do not give developers easy ways to select exactly the features that apply to specific projects. At the same time, bringing the source code of the framework to a state ideally corresponding to a certain project may require a level of experience from the team that it may not have. A similar situation in itself may become the reason for the search for the framework.



Suppose you download 100 KB of CSS. I would say that is a lot. (At the moment when I write this, css-tricks.com uses about 23 Kb of CSS. There are quite a lot of pages and templates. I didn’t do anything special to reduce the size of CSS.) There is a suspicion that you are not using some of this amount of code. And maybe you find some evidence of this. I see a reason to sound the alarm. If you have a 100 Kb jpg file that you can compress to 20 Kb by processing it with some kind of tool, then this is great, and it’s worth it. But if you do something similar with CSS, then this is much more important. The fact is that CSS is loaded at the beginning of the page loading and is a resource that blocks rendering. JPG files are not such resources.



Situation analysis with Chrome Developer Tools



The Chrome Developer Tools window has a Coverage



tab. With its help, you can find out how much loaded CSS and JavaScript are actually used on the page being analyzed. For example, now I went to css-tricks.com. Below is what I saw on the Coverage



tab.









Chrome Developer Tools, Coverage Tab



Here I see that 70.7% of my style.css



file is not used. I think that there is nothing wrong with that. The remaining unused part of CSS is used on some other pages of the site. On this site I do not use some large style library. I myself wrote every line of CSS, so I doubt that 2/3 of the CSS are out of place globally.



I assumed that when working with the Coverage



tab, you can start “recording” and wander around the site, watching how the percentage of unused resources falls as different pages are displayed in the browser. But, unfortunately, when the page is refreshed, the contents of the Coverage



tab are also updated. As a result, this tool is not particularly useful in determining the percentage of resource usage across multiple pages. Perhaps this is not only if you analyze a single-page application.



It’s unpleasant for me to say this, but analyzing the site using the Coverage



tab turned out to be almost pointless. What I saw, these 70.7%, is a terrible picture that plays on my doubts, but this analysis does not give me anything concrete, as a result I can only worry about something wrong on my site.



Perhaps this analysis of the site will be the very mechanism that will lead you to the idea that you need to find and remove CSS code that loads, but is not used in your project.



My primary problem



In finding and removing unused CSS, the following concerns me the most. Suppose someone looks at the results of an analysis and sees unused CSS snippets.









Unused CSS Snippets



He thinks: “Great, I delete everything superfluous!”. The superfluous is removed, and then it turns out that it was not at all superfluous, and that its removal led to big problems with styling on the entire site. Here's the thing: you can be completely sure that some CSS selector is not used, only if you conduct research on the following plan:



  1. You need to check every page of the site with a tool like the Coverage



    tab.
  2. In this case, you need to execute all the JavaScript code.
  3. This must be done with all possible options for the state of the application.
  4. And, in addition, you need to check all this with all possible options for the media queries used.


If only the website’s home page is checked, this is not taken into account. Studying all the top-level pages is also not considered a real test. You need to go through all the pages, examine the site in situations that its developer may not immediately remember, check all borderline cases. Otherwise, everything may end with the removal of the styling of the drop-down list of credit cards in the pop-up modal window for users with a disabled account who enter the system during the grace period for paying for a new subscription and at the same time have a valid gift card.



Something like this is too complex for automated CSS parsers. They are not able to perfectly perform such checks, especially if you consider the analysis of the site in a situation of uncertainty. We are talking, for example, about researching projects in different browser contexts (different screen sizes, different browser capabilities, different browsers), and taking into account the impact of third-party libraries on the site.



And now I want to show an example of how all the problems that I just talked about look in practice.



PurifyCSS Online



I decided to try optimizing css-tricks.com using the PurifyCSS Online resource. You can pass links to it, and it immediately produces CSS ready for use. I “fed” css-tricks.com to this site and I had new CSS code at my disposal. This is what happened after I used this code.









On the left is the usual view of css-tricks.com. On the right is the result of applying new, “refined” CSS. This new code lacked a lot of what is needed for various pages of the site



PurifyCSS allows you to analyze based on many links (which is nice), but on css-tricks.com there are tens of thousands of links. Many of them lead to similar, in terms of CSS, pages, but on each of these pages there may be something that is not used elsewhere. In addition, I got the feeling that PurifyCSS does not run JS-code, because after “cleaning” my CSS everything that was output to the pages using JavaScript turned out to be unstyled. Even the styles for the pseudo-classes :hover



.



Probably, I have already said enough to make you understand that it is not by chance that I trust such tools so little.



Purify CSS with PurifyCSS as part of the project build process



PurifyCSS is probably used more often as a tool used to build a project than as an online CSS cleaner. The project documentation contains instructions for its use when using Grunt, Gulp and webpack. For example, processing files by templates:



 var content = ['**/src/js/*.js', '**/src/html/*.html']; var css = ['**/src/css/*.css']; var options = {  //  CSS    .  output: './dist/purified.css' }; purify(content, css, options);
      
      





This approach allows for much greater accuracy. The materials of the site that are submitted for analysis can be a list that includes each template, each fragment used to build pages, and every JavaScript file. It may turn out that such a list of resources is not easy to maintain, but it allows you to consider everything that can be taken into account. This, however, does not apply to the content of pages lying in certain repositories (such as blog posts that are stored in the database), and to third-party JavaScript code, but perhaps this is in some cases unimportant, or maybe the developer will be able to somehow take into account the CSS needs of such resources.



PurifyCSS rival documentation PurgeCSS has a warning regarding the resource handling method used by PurifyCSS. Namely, we are talking about the fact that PurifyCSS can work with resources of any type, and not just with HTML and JavaScript. PurifyCSS in the course of work analyzes all words in files and compares them with selectors in CSS-code. Each word is considered a selector. That is - many selectors may be mistakenly recognized as being used on the site. For example, in the textual content of a file, in a regular sentence, a word may be present corresponding to a certain CSS selector.



PurifyCSS is worth remembering about this. This tool searches for CSS selectors in the site materials using an extremely simple algorithm. This, on the one hand, is a sensible idea, and on the other, it is quite dangerous.



UnusedCSS Service



Manual tuning of a tool, carried out so that this tool would analyze every page, so that it would examine it from all possible points of view, is, of course, a boring routine. Moreover, such work should be carried out on a daily basis, since the analyzed information about the site should be updated with new data as the project develops. There is one online service called UnusedCSS . He independently bypasses the pages of the site, saving the developer from a lot of monotonous work. This service is sufficient to transmit a single link to the site.



I signed up for a paid subscription to this service and analyzed css-tricks.com with it. I must admit that after I looked at the results, I had the feeling that they looked much more accurate than what I had seen before.









Analyze css-tricks.com with UnusedCSS. The report says that the site uses 93% of the loaded CSS code. It seems close to the truth to me, since I manually wrote all the CSS code for this site



The service, in addition, allows you to download a file with cleared CSS code and offers the ability to manage the contents of this file. For example, this is enabling and disabling selectors that the developer would like or would not like to add to the CSS code. Suppose a developer sees a class name, which, according to UnusedCSS, is not needed on the site, but the developer knows for sure that he cannot do without this class name. As a result, the code mistakenly recognized as unnecessary can be marked as necessary. Other features of UnusedCSS include working with prefixes and removing duplicate selectors.



I really liked the fact that UnusedCSS gave me much more accurate results than other tools. However, there is too much “noise” in the data generated by this service, and I also don’t yet know how to include UnusedCSS in the regularly repeated process of building a project and putting its new versions into production.



Read the second part



Dear readers! Have you encountered the problem of having unused CSS code in your projects?








All Articles