Due to some circumstances, this blog is now up for sale, for more enquires contact: Plushista@gmail.com
RealcomBiz
Pin It

Remove Unused CSS to Reduce your Stylesheets Size

by Unknown | Wednesday, August 20, 2014 | | 27 Comments

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!".

27 comments : 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
  2. Thanks for publish a great article!

    http://www.gossip-lankanews.com

    ReplyDelete
  3. coolsquare this site about web development and we graphics

    ReplyDelete
  4. VMware is a cloud computing software and virtualization provider for x86-compatible computers. It is mainly based on the ESX bare metal hypervisor, supporting virtual machines.Keep sharing more about VMware.
    Regards,
    VMware Training in Chennai | VMware course in Chennai

    ReplyDelete



  5. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..
    please sharing like this information......
    Android training in chennai
    Ios training in chennai

    ReplyDelete

  6. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving.. very specific nice content. And tell people specific ways to live their lives.Sometimes you just have to yell at people and give them a good shake to get your point across.
    Web Design Company
    Web Development Company
    Mobile App Development Company

    ReplyDelete
  7. It’s a great and useful post. Keep sharing such kind of noteworthy information.

    Vmware cloud certification | VMware courses in Chennai | Vmware cloud Training

    ReplyDelete
  8. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I have bookmarked more article from this website. Such a nice blog you are providing ! Kindly Visit Us @ Tours and Travels in Madurai | Best Travels in Madurai | Madurai Travels

    ReplyDelete
  9. Highly informative article. I was searching for such quality articles for a long time. I am happy that I found this article. Keep going!
    Data Science Course in Chennai | Data Science Training in Chennai

    ReplyDelete
  10. Wow it is really wonderful and awesome thus it is veWow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your site.ry much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your site.vmware training in bangalore

    ReplyDelete

Recent Posts

Let's Connect

Site Links

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