Use PHP to Gzip and Optimize CSS Files
If you have been following the best practices for website optimization published by Yahoo’s Exceptional Performance team, you know the importance that using gzip to compress files and making fewer HTTP requests can have on website speed.
While doing some research, I came across a number of powerful techniques that uses PHP to optimize CSS files. By combining these techniques, I was able to achieve some impressive enhancements resulting in a 71% reduction in the size of my CSS files.
It’s a combination of 3 techniques actually. All the techniques are covered in more detail over at Cats Who Code, but here is a quick rundown of what I like and dislike about each one.
Paul Stamatiou Method
I like the error checking in Paul Stamatiou’s method for two reasons: 1) it checks to see if the zlib extension is loaded and 2) the gzip compression. I don’t like that you have to rename your CSS files with a PHP extension which causes my IDE to highlight the syntax as PHP rather than CSS and that the snippet has to go in all CSS files.
Perishable Press Method
In Perishable Press’ technique, I like the gzip compression and the cache checking. Again, I don’t like that you have to rename the CSS files with a PHP extension and that the snippet has to go in all of CSS files.
Reinhold Weber Method
Reinhold Weber’s technique combines all the CSS files into one file via includes before sending it to the browser, does not require you to rename your CSS files with PHP extension, and strips comment out by removes comments.
The downside is that the regex that removes all the whitespace caused some issues with CSS shorthand and makes it harder to use Firebug to troubleshoot layout issues since the entire content of the CSS file resides on line 1.
My Modified Technique
To put this to use, create a file called
styles.php in the same folder as your CSS files.
Paste in the following code:
You will then need to update the path to the CSS file in the head of your HTML or PHP file to point to the
styles.php file that you created.
As you can see from the image below, the 2 CSS files were output as 1 file and the size went from 11.2KB to 3.2KB. The comments were also removed from the file, but whitespace was retained to aid troubleshooting if there are any layout issues.
This technique is a powerful and simple way to reduce page download size and speed up your site that will work with most PHP installations, even those on shared hosting that don’t have
mod_deflate turned on in their Apache configuration.
I’ll definitely put this method to use on my redesigned site which will debut later this month and begin using it as part of my standard process for all new projects.