Combining CSS files with htaccess
January 03, 2012 at 2:18 PM
I first came across this concept while investigating the HTML5 broilerplate a couple years back. For a while, I wanted an elegant solution to combining multiple includes into one. And this was the key.
Why use only one CSS file, and one JS file?
Simple. Load time. A browser only downloads 3 files at a time and therefore the less includes you have, the faster your browser can at least move on from css/js and onto the images.
In 2011 Vivid started building a really large web application, which had various section from the "public" side, to the "administrative" side, and of course, several other pieces. It made sense to us, that instead of having 1 css file to manage, we might break down the css into a public css file, the management css, the storefront css etc etc. All for the same reasons a programmer breaks down a page into includes for a header, footer and sidebar etc etc... The problem is we ended up with about 8 CSS files. And including 8 css includes seemed a bit excessive. So we knew, we had to bring it back down to one CSS file, and one JS file.
Okay, so why not use @import within your CSS file?
That's exactly what we thought we should do. Until we used firebugs Net tab, and noticed that it didn't download it as one file, but rather, 8 files!
So how do you use htaccess to combine these files?
<FilesMatch "\.combined\.(js|css)$"> Options +Includes SetOutputFilter INCLUDES </FilesMatch>
Once we do that, we create a CSS file called styles.combined.css and use regular Server Side Include tags like you would in an HTML document. So open up "styles.combined.css" and simply add in the includes as seen below