For your pages to load as quickly as possible, every resource needs to be optimized and compressed. As images are the greatest contributor to the overall file size of most sites, they should typically be the web developer’s first and primary area of concentration, which I’ve covered in a previous article. After that, other site resources should be compressed in terms of how frequently they are used, including the stylesheet.
Optimisation of CSS is a three-step process, and you’ll usually need a combination of tools to gain the best results.
- Remove style rule irrelevancies and redundancies
It’s common for a great deal of “cruft” to be added to stylesheets during development: CSS rules are often repeated haphazardly, or not used at all in the final version of the site. A redundancy checker such as Dust-Me checks your CSS rules against the actual HTML used by working through the local Sitemap, while CSSCSS (a Ruby gem) works on the CSS alone, looking for duplications in code.
- Order Declarations
You’ll get the greatest result out of gzip compression (discussed separately) if the CSS declarations are placed in the same order in your stylesheet each time. CSS Comb (available online and as an extension for most IDE’s) provides a number of resorting algorithms to do so.
Running this step early and frequently in your code generation can also make your CSS easier to read.
- Step Three: Compress to styles.min.css
The final compression step removes optional spaces, carriage returns, comments, and other unnecessary text from your CSS code. While it will work exactly the same, your CSS code will now be much more difficult to read, so it should be saved as a new, separate file (typically styles.min.css) that your pages will link to.
Some minifiers take things a little too far, removing code they don’t understand (such as vendor prefixes and CSS3) – you should keep an eye out for these behaviors if you go looking for other compressors.
Following these steps with server-side gzip compression will often result in size reductions of 20% or more in your site’s stylesheet, which translates into faster page load times and lower bandwidth costs.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.