Supercharging Javascript, Part 2: GZip Everything

Previous: Make as Few HTTP Requests as Possible

In these days of 50+ Mbit residential internet connections there is a tendency to not give a second thought to bandwidth but this is an error for four reasons:

  1. Not everyone is on a high speed connection. I still know (a few) people who use dialup;
  2. You or your client or employer are paying for your site's bandwidth;
  3. Latency is not (completely) inversely proportional to bandwidth. So it can still affect load time; and
  4. With the rise of mobile broadband through 3G and similar networks, data usage and load times are much more important than they are for landline connections.

Luckily PHP comes to the rescue and we only need to add one line to our script.

// These no longer even need to be under the document root
define('SCRIPT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/script/');

$bundles = array(
  'site' => array(


$site = $_GET['site'];
if (!isset($bundles[$site])) {
  error_log("javascript.php: Unknown bundle '$site' requested");
header('Content-Type: text/javascript');
foreach ($bundles[$site] as $file) {
  if (@readfile(SCRIPT_DIR . $file) === false) {
    error_log("javascript.php: Error reading file '$file'");

This turns on PHP output buffering and enables the GZip handler. This handler does all the hard work of determine if the client will accept gzip encoding, based on it's HTTP headers.

Next: Minify Everything


Anonymous said...

What about IE6's gzip decompressing bug?

darwin said...

thx for sharing's really compress my javascript 50% :)

Post a Comment