suburban glory

A Blog in Suburban Glory:
Web Dev Ideas and Inspiration

How to dramatically compress your CSS and Javascript files by using PHP

|| Category: PHP ||

This is a method that I use to shrink Javascript or CSS files using PHP. You don't need any knowledge of PHP to try this out as you can just cut'n'paste the required code.

I've used it quite a few times now and it will compress your file by around 50%. Which, if your CSS file is over 1,000 lines or you are using a Javascript framework like Prototype, will decrease the download time.

The files should be read fine by every browser.

So here is what you do.

Take the contents of the CSS file and place it in PHP file with a .php extension. Put the following line of code at the top of the document:

<?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header("Content-type: text/css"); ?>

Then at the very bottom place this line of code:

<?php if(extension_loaded('zlib')){ob_end_flush();}?>

And that's it. Now link from your HTML head to this PHP file rather than the CSS file.

For Javascript it is a case of doing the same but change the content type like so:

<?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header('Content-Type: text/javascript'); ?>

I don't use this for HTML but I do place the following in my .htaccess file:

# BEGIN GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
# END GZIP

As a warning, use this method only if you are hand coding and not if your are using a CMS or blogging platform. You'll find that a CMS will have this written into their core code or you'll be able to use a third-party add-on to achieve the same results.

Comments

Khalilullah || Thu 10th Sep 2009

The guys at the http://httpd.apache.org/docs/2.2/mod/core.html#addoutputfilterbytype say that addoutputfilterbytype is deprecated.

Bertie || Thu 12th Jan 2012

Articles like this are an example of quick, helpful answers.

You can add comments below.
Auto-paragraphing is enabled. Double newlines will be converted to paragraphs.

Allowed tags: a, abbr, acronym, b, blockquote, caption, cite, code, dd, del, dfn, div, dl, dt, em, i, ins, kbd, li, ol, p, pre, s, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, var.

If you wish add code examples then please do so between the following tags:

<pre><![CDATA[
Place code here
]]></pre>







mainland