Self-coded RSS A blog on Python, WebOb, programming technique and miscellaneous projects by Sergey Schetinin.
Minifying CSSOver the years I’ve come up with a number of principles that allow me to produce clean, readable, yet extensible code. I want to share them, but I also want you to see that they work and to understand how they are applied. In the end I want to see them used “in the wild”, and the average code quality to go up if ever so slightly. So what I will be doing is writing a bunch of code examples, designs and comparisons and later reuse them to demonstrate that certain choices and basic programming principles lead to better code. Let’s start with writing a way to to compact CSS code. There are a number of existing libraries for this, but we will write one from scratch nevertheless. All we need is a function to take a string (CSS) and return a string (minified CSS). The most basic minification would be to collapse all whitespace and newlines, so let’s start with that:
The
Now let’s remove comments as well:
The
We’ve already made most of the progress we can get and additional compaction will not yield significant savings in CSS code size, but let’s add a few more rules. We can remove whitespace in the beginning and the end of the file and around separators. Remember that we’ve compacted the whitespace and there are at most one character paddings at this point.
Note the use of backreference
One thing we need to work around is that by stripping the spaces around the colons we will turn While we are at it, let’s precompile those rules as well. Here’s the entire implementation:
I wanted to add comments to those rules, but check this out: when we decided to precompile them, we’ve also had to assign the names to them, and those work just as well for documentation purposes, if you ask me. Now, tell me if this was a waste of time, and we should have just used an existing minifier? Of course there are a couple more things we can collapse, we can even go for a parse-optimize-output approach. But seriously, from a practical standpoint, that’s a waste of time. (Could be useful for self-educational purposes though). To be fair, this minifier can stumble on some CSS rules for example Here are some other implementations for comparison:
Some points to consider:
|