Compress and cache your CSS with PHP

I’ve recently been a bit obsessed with loading speed and I’ve done some research on how to speed up things by compressing and caching and headers etc.

I’ve tried some different plugins for WordPress that supposibly should compress all my CSS and JavaScript, but I never got them to work at all. So I decided to make my own PHP script for css compression. I called it PHP CSS Compressor and it’s available on GitHub. It’s not very advanced, but does what it should. Feel free to fork it.

It works by removing all spaces and line breaks and moves everything into one row. It loops through each file in order, so be sure to add them in the correct order if you have some rules that override other rules.

Every time the PHP file is called, it looks for the cached file and compares the date between that and the newest css file in your list. If the cached file is newer, it simply delivers the cached file, but if you recently changed some rules, it will re-compress all files into the cached target file and deliver it.

Once configured, you’ll never have to worry about it!

It’s fairly easy to configure. All you need to do is to feed it with the paths to your different CSS files and then remove all references to CSS files in your header.php and point instead to the php-file. The PHP-file will deliver a compressed cached file with all your CSS.

<link href="<?php bloginfo('template_url'); ?>/css/csscompressor.php" rel="stylesheet">

Also, if you have compression available on your Apache web server you can add the following to your .htaccess to enable compression of all text files like CSS, HTML and JavaScript .

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

<IfModule mod_expires.c>
ExpiresActive On
############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires
<FilesMatch "\.(ico|jpg|jpeg|png|gif|js|css)$">
ExpiresDefault "access plus 1 year"
</FilesMatch>
</IfModule>

Share your thoughts on this

Your email address will not be published.