CSS and JavaScript files are simple plain text files with large amounts of unused space. Compressing all your style sheets into one page using PHP and gzip is simple and can easily cut file download time in half (and reduce the number of files that need to be downloaded).

First step: replace all your style sheet links in the head of your html document with a link to your new PHP-generated compressed style sheet. I keep all my style sheets in a directory named “css”, and the PHP script is in the same directory and named “all.php”. I access this file just like a normal style sheet.

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))

ob_start("ob_gzhandler");
else

ob_start();

header('Content-type: text/css');
header('Expires: Fri, 21 Dec 2012 00:00:00 GMT');

$files = array('jquery.lightbox-0.5.css', 'main.css', 'nav.css', 'content.css', 'objects.css');

for ($file = 0; $file

The first four lines tell PHP to compress the file it returns. The next line serves the file as CSS (even though it has a PHP extension). The line after that sets an expiration date far in the future (by defauly most browsers will not cache this file, but instead will reload it for every single page since it is a PHP script). The expiration date will ensure that the visitor to your site only downloads the file once.

Finally, create an array with a list of the files you wish to compress, and use a for loop to output them all – compressed. I managed to cut out about 50KB in this example, but the biggest advantage comes from reducing the number of file requests to the server (which will make a big difference even on the fastest connections).

You can follow the exact same process for JavaScript, but make sure to change the Content-type header from text/css to text/javascript. Together these techniques can chop of more than 50% of the size of your CSS and JavaScript files and greatly reduce the number of files a viewer must download.