Gzipping your pages to save bandwidth

Ok I’ve been playing with Javascript frameworks like Jquery and Prototype. Now by default Jquery is 54KB and Prototype is 130KB (at the time of writing this). As you can see these are not small files. Now this is where gzip comes in. An easy way to describe gzip is that your server zips up the file before sending it to the web browser and the web browser then unzips it. Anyway by gzipping these two files using some PHP I have got Jquery down to 19KB and prototype down to 30KB!!!!

So we have Jquery:
Original Size: 54 KB
Gzipped Size: 19 KB
Data Savings: 64.81%

and prototype:
Original Size: 131 KB
Gzipped Size: 30 KB
Data Savings: 77.1%

All testing done using mod_zip test.

Anyway on to the code.

Ok to send something gzipped we need to use PHP’s buffer and so one of the first things we need to do is turn it on.

<?php
ob_start('ob_gzhandler');
?>

We would then just put our Javascript (or normal HTML) after the ?>

The ob_gzhandler is a function in PHP that checks if a browser supports gzip compression or not and if it doesn’t then PHP will not gzip the buffer.

Finally we tell PHP that we are done with the buffer and we want it to flush the buffer. Flush just means it sends the contents of the buffer to the browser and then closes the buffering.

<?php
ob_end_flush();
?>

And that’s it. So in a nutshell.

<?php
 ob_start('ob_gzhandler');
?>
 
<!-- Your Javascript or HTML here (or even PHP code) -->
 
<?php
ob_end_flush();
?>
  1. Very nice blog about the Java Script frameworks.I think these kinds of blogs are very informative and useful for the users Especially for developers,In this way the developers can get some tips and guidelines about the HTML and Java Scripts.

Leave a Reply

Post Popularity Graphing by Knowledge Ring