see whatever…

jump to menu

December 26, 2008

combine and minify CSS

Filed under: CSS,cssutils — Tags: , , — see @ 12:55 pm

I have been working on minifying CSS for quite some time now and had written a simple based CSS handler which does exactly that. Actually it simply uses the minify option of cssutils

Additionally the handler does combine all imported stylesheets of a given proxy sheet into a single one. Nice for development as you can split sheets into as many as you like but deploy only one. So you may have the following stylesheet style.css:

/* proxy sheet */
@import "basics.cs";
@import "layout.css";
@import "forms.css";
/* etc... */

(I normally separate styles into something similar).A given HTML page always references the single stylesheet style.css which would even work without a combinator as @imports will be loaded by the browser anyway. But for deployment or when using the simple combinator handler style.css will contain all rules from all imported sheets resulting in only a single HTTP request. If additionally minified after combination the savings on load time in most cases is substantial.

For the next release of cssutils I added a combinator function to cssutils itself:

proxysheet = cssutils.parseFile(PATH_TO_CSS) # or use parseUrl etc
combinedsheet = cssutils.resolveImports(proxysheet)
print combinedsheet.cssText

Based on this I thought it would be nice to have a service which does just that, resolve all imports in a given sheet, minify it and return it. So I started the CSS Minifier at GoogleAppEngine (GAE). It has a basic frontend where you enter an URL, may optionally select advanced options (for now the error level below which errors are simply swallowed, the target encoding which may currently be UTF-8 or ASCII and the option if the imports should actually be resolved).

Additionally it may be used as a simple service which returns a combined and minified sheet or in case of any errors a HTTP 400 BAD REQUEST with the error log.

The only problem on GAE was that it prevents usage of urllib/urllib2 to actually fetch the content of URLs. But it has it’s own API for that so no big problem to rewrite the fetching code. For the next cssutils release I actually added the code for GAE into cssutils itself. If cssutils thinks it runs on GAE it uses the GAE specific fetcher code, else urllib2 as before.

To detect if a script is running on GAE for now I try to “import google.appengine”. Not quite sure if that is enough but for now it seems to work.

Anyway, hope this service may be useful.

Powered by WordPress