Create a new file called "jquery.php" and inside put this code:
ob_start('ob_gzhandler'); echo join('',file('jquery-1.2.3.pack.js')); ob_end_flush();
Test this in your browser to check that everything is working ok, and to see how much has been saved with using this technique load up firebug in firefox and click on the "net" tab to see the filesize before and after.
Compressing Multiple Scripts at Once
ob_start('ob_gzhandler'); echo join('',file('jquery-1.2.3.pack.js')); echo join('',file('common.js')); echo join('',file('more_code.js')); ob_end_flush();
In the above example all 3 files will be loaded, compressed and sent to the browser as one single file. As well as reducing the file size this will also reduce the number of server round trips and will shave a few more ms from the load time.
How it works
The "ob_start()" php function turns on output buffering which means than any output generated by the script will be saved into an internal buffer instead of being outputted to the browser. This buffering will continue until the "ob_end_flush()" method is used to flush the internal buffer and output everything that has been produced by the script.
As of PHP version 4.0.4 the "ob_gzhandler" was added as a callback mechanism to allow PHP to send gz-encoded data to browsers that support compression. The beauty of using this type of compression is that everything is handled on the server so that this little script will work in all browsers.
Posted on 9th April 2008