Using PHP to Dynamically Compress CSS and JavaScript

CSS and JavaScript files are simple plain text filessets an expiration date far in the future (by defauly
with large amounts of unused space. Compressing allmost browsers will not cache this file, but instead will
your style sheets into one page using PHP and gzip isreload it for every single page since it is a PHP script).
simple and can easily cut file download time in halfThe expiration date will ensure that the visitor to
(and reduce the number of files that need to beyour site only downloads the file once.
downloaded).Finally, create an array with a list of the files you
First step: replace all your style sheet links in the headwish to compress, and use a for loop to output them
of your html document with a link to your newall - compressed. I managed to cut out about 50KB in
PHP-generated compressed style sheet. I keep all mythis example, but the biggest advantage comes from
style sheets in a directory named "css", and the PHPreducing the number of file requests to the server
script is in the same directory and named "all.php". I(which will make a big difference even on the fastest
access this file just like a normal style sheet.ifconnections).
'],You can follow the exact same process for
r('Content-type: text/css');header('Expires: Fri, 21 DecJavaScript, but make sure to change the
2012 00:00:00 GMT');Content-type header from text/css to text
$files = array('jquery.lightbox-0.5.css', 'main.css',javascript. Together these techniques can chop of
'nav.css', 'content.css', 'objects.css');for ($file = 0; $filemore than 50% of the size of your CSS and
The first four lines tell PHP to compress the file itJavaScript files and greatly reduce the number of
returns. The next line serves the file as CSS (evenfiles a viewer must download.
though it has a PHP extension). The line after that