Since I started thinking about building this site, one of my goals has been to try out some optimization features that may be available. One of those features was the ability to compress CSS files. By compressing CSS files, a site will load faster because there is one less request that the browser has to make. But I wanted to still take it one step further. I wanted to remove the whitespace from the CSS as well, therefore compressing and shrinking the size of the CSS.
Originally I was going to use django-compressor, but I found that it didn’t actually compress the CSS files, but rather it just joined them. Then I found django-css, which used django-compressor but also add a filter to actually compress the code.
I know that the names are terminology are confusing but there’s nothing I can do about that. So for future reference, when I say compress I mean the compression of the code and the removing of unnecessary characters. I will use the full name when referring to django-compressor.
Upon adding the compressor app from django-css, it worked exactly like django-compressor. So I was left with implementing the filter to compress the CSS. Django-css comes with some filters for CSSTidy and YUI. I didn’t really want to mess with some of those libraries; I felt that they were a little bloated for what I wanted to do. So a quick search found python library called slimmer at http://pypi.python.org/pypi/slimmer/.
Slimmer did exactly what I wanted. It was no frills, simply removed comments, whitespace, and line breaks. So I was left with implementing the filter. I actually had a found an article elsewhere on the web that helped me get started, but I was not able to find it at the time of this writing… but thank you anonymous author.
To setup the filter, I created a new folder in the django-css folder filters and called it slimmer. Then I created the __init__.py file and put this code inside:
from compressor.filters import FilterBase, FilterError
def output(self, **kwargs):
filtered = slimmer.css_slimmer(self.content)
Then I just added this line in my settings.py to tell compressor to use the filter:
COMPRESS_CSS_FILTERS = ('compressor.filters.slimmer.SlimmerCSSFilter',)
And that was that. I ran it and it worked great. All whitespace was out, all comments were out, and all the code was one line. Very efficient.
Well I hope that this was able to help. I’m sure that there is room for improvement, so leave any tips or suggestions below.