Compressing CSS and JavaScript

Stylesheets and script files can often get quite large. Although they will be cached by the browser there is still the time delay (and bandwidth hit) of the first loading, which according to Yahoo! is more often than you think. Here's a quick and dirty method of using PHP with gzip compression to send your CSS, Javascript and whatever else compressed to browsers.

Just create a file called

style.css.php (or whatever you prefer) in the same directory as your style file. Then add this code to it:

The main parts are the ob_start and require calls. ob_start starts output buffering and tells the buffer to use gzip compression on the output of the script. require will load the contents of the file specified. If you want to use this for JavaScript, make sure you change the "text/css" on line 3 to "text/javascript".

Now you just need to change the contents of any relevant <link> or <script> tags in your HTML to point to style.css.php instead of style.css and you're set! Feel free to play around with the expires offset – you might want to set it to 10 years in the future for long-term caching but make sure you change the name of the file whenever it's updated, otherwise the browser might not load the newer version.

If you have multiple CSS or JavaScript files that you want to load then you might like to check out Ed Eliot's automatic merging and versioning script.