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. But we tell PHP to gzip a file when starting the buffer so first we check if the web browser actually supports gzip. The browser tells the server that it supports gzip by sending it as part of it's HTTP_ACCEPT_ENCODING header. So use a simple stripos will tell us if the browser supports gzip. I use stripos and not strpos just in case a browser uses Gzip instead of gzip.
CODE:
if(stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
And so if the browser supports gzip we turn the buffer on with
ob_gzhandler for the callback otherwise we just want a normal buffer.
CODE:
<?php
if(stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
ob_start('ob_gzhandler');
}
else
{
ob_start();
}
?>
We would then just put our Javascript (or normal HTML) after the ?>
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.
CODE:
<?php
ob_end_flush();
?>
And that's it. So in a nutshell.
CODE:
<?php
if(stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
ob_start('ob_gzhandler');
}
else
{
ob_start();
}
?>
<!-- Your Javascript or HTML here (or even PHP code) -->
<?php
ob_end_flush();
?>