RealcomBiz
Pin It

Remove Unused CSS to Reduce your Stylesheets Size

by Durodola Ridwan | Wednesday, August 20, 2014 | | 1 Comment

We all like creating new stuffs and updating our site theme to meet up with the latest trends. We added new features, let's say a widget and after some times, we believe it is outdated and decide to trash it out. Most times we remove the widget forgetting to dig-out the styles from the stylesheets. The styles becomes an unused or dead CSS selectors.

It is important to remove the unused CSS selectors to speed-up browser rendering of your website. And even if the effect of this unused selectors on your site performance is minimal, it would make your task of maintaining CSS easier if the files are kept clean and well-structured.


 Google also recommends the removal of unused CSS:

"Before a browser can begin to render a web page, it must download and parse any stylesheets that are required to lay out the page. Even if a stylesheet is in an external file that is cached, rendering is blocked until the browser loads the stylesheet from disk. In addition, once the stylesheet is loaded, the browser's CSS engine has to evaluate every rule contained in the file to see if the rule applies to the current page. Often, many web sites reuse the same external CSS file for all of their pages, even if many of the rules defined in it don't apply to the current page.

The best way to minimize the latency caused by stylesheet loading and rendering time is to cut down on the CSS footprint; an obvious way to do this is to remove or defer CSS rules that aren't actually used by the current page."

While there are several tools that lets you locate unused CSS selectors within your site pages, among the best are:

Google Chrome Audit Tool

Google browser has an awesome but overlooked feature built in its Developer Tools. It's called the "Audit tool". To make use of this excellent feature, follow the below steps:
  • Open any page of your website inside Google Chrome and then launch the Dev Tools available under File > Tools > Developers Tools (or press SHIFT + CTRL + I).
  • Click on the Audits tab within the Developer Tools window.
  • Make sure the "Web Page Performance" and "Reload Page and Audit on Load" options is checked.
  • Now click the "Run" button

The CSS audit tool will start digging out unused CSS on the specified page. You still need to do the gruntwork of locating them in your stylesheet and removing those rules.

If you're going to do this, make sure you run it against lots (if not all) of your pages so you aren't removing selectors that are in use, just not on every page. You can find the count of various selectors in the combined result set, maybe using Google Sheets, and the selectors with the highest count can probably be "safely" removed. This rule also applies to any other tool you might use.


Firefox: Dust-Me selectors extension

For Firefox fan, there is something for you too. Sitepoint released a Firefox extension called Dust-Me selectors, which is a bit advanced than Chrome audit tool and it happens to be my favourite. Dust-Me extracts all of the selectors from all of the stylesheets on the page you’re viewing. It then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they’re encountered. Dust-Me also gives you the option of testing pages individually or spider an entire site, and you'll end up with a profile of which selectors are not used anywhere.


UnCSS

Giacomo Martino’s excellent UnCSS tool gives us the ability of removing unused CSS to help keep our site's extra lean. It works across multiple files and supports JavaScript-injected CSS. It can also work in conjunction with other javascript build systems, such as Grunt or Gulp uncss.
The process by which UnCSS removes the unused rules is as follows:
  • The HTML files are loaded by PhantomJS and JavaScript is executed.
  • Used stylesheets are extracted from the resulting HTML.
  • The stylesheets are concatenated and the rules are parsed by css-parse.
  • document.querySelector filters out selectors that are not found in the HTML files.
  • The remaining rules are converted back to CSS.

Like just about every NodeJS-based utility, you can also take advantage of its JavaScript API. Here's an example:

var uncss = require( 'uncss' );
var files   = [ 'my' , 'array' , 'of' , 'HTML' , 'files' ],
options = {
ignore       : [ '#added_at_runtime' , /test\-[0-9]+/ ],
media        : [ '(min-width: 700px) handheld and (orientation: landscape)' ],
csspath      : '../public/css/' ,
raw          : 'h1 { color: green }' ,
stylesheets  : [ 'lib/bootstrap/dist/css/bootstrap.css' , 'src/public/css/main.css' ],
ignoreSheets : [ /fonts.googleapis/ ],
urls         : [ 'http://localhost:3000/mypage' , '...' ], // Deprecated
timeout      : 1000 ,
htmlroot     : 'public'
};
uncss(files, options, function (error, output) {
    console.log(output);
});
/* Look Ma, no options! */
uncss(files, function (error, output) {
    console.log(output);
});
/* Specifying raw HTML */
var raw_html = '...' ;
uncss(raw_html, options, function (error, output) {
    console.log(output);
});


Mincss

mincss is a python script. As its creator Peter Bengtsson explains, mincss is a tool that when given a URL (or multiple URLs) downloads that page and all its CSS and compares each and every selector in the CSS to find out what isn’t used. The result is your original CSS file with those unused selectors (not found in your HTML) removed.

The way it works is that it parses the CSS payload (from inline blocks or link tags) with a relatively advanced regular expression and then loops over each selector one at a time and runs it with cssselect (which uses lxml) to see if the selector is used anywhere. If the selector isn't used the selector is removed.

Other projects

Some other developers have been creating awesome tools that helps in detecting unused CSS within any page, and worth mentioning:

Conclusion

I think this are great tools for all of us who either just downloaded a bloated CSS framework or working with a heavy modern UI framework such as Twitter Bootstrap, Zurb Foundation or Adobe TopCoat.

Every single tool mentioned in this post worth giving a try especially the Audit tool and UnCSS. And when testing, don't forget to run this across multiple pages in order to be on the safe side.



Go Social:

Subscribe For Free Updates!

*Please confirm the email sent to your inbox after clicking "Sign Up!".

1 comment : Post Yours! Read Comment Policy ▼
PLEASE NOTE:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

  1. http://www.aktwall.com/post/1336/remove-unused-css-to-reduce-your-stylesheets-size

    ReplyDelete

About Me

My Photo
Durodola Ridwan is a Professional blogger, SEO Consultant, Certified Web developer/designer and founder of www.realcombiz.com. He love writing about Blogging tips, SEO, and play around with codes. You can connect with him on facebook, twitter @realcombiz, and Google+.

Recent Posts

Let's Connect

Site Links

Copyright © 2014 RealcomBiz. All Rights Reserved.
Powered by Blogger