Sunday, July 21, 2013

Compress External Javascript with gzip in PHP


If you are using an external Javascript, you can compress the content before sending it to the browser using PHP.

Here's the solution (simplified for easy reference):

<?php

error_reporting(0); // make sure it is not reporting any warning that will ruin the output

$js = <<<MYJAVASCRIPT
.
.
.
MYJAVASCRIPT;

// Optional: The following three lines of extra codes are to downsize the Javascript further
//$js = preg_replace('|//[^\r^\n]+(\r\n)|','',$js); // Remove Javascript Comment PC version
//$js = preg_replace('|//[^\n]+(\n)|','',$js); // Remove Javascript Comment non-PC version
//$js = preg_replace('/[\r\n\t]/','',$js); // Remove all the newlines and tabs


$compressedJS = gzencode($js,6); // compression ratio = 6

header("Content-type: application/x-javascript");
header("Content-Encoding: gzip");

echo($compressedJS);


?>


You can check the final compressed size easily using Google Chrome Inspect Element (Network) tool:


Before Compression


After Compression

Please ignore the latency as it varies every time I run the page.

If your javascript/HTML/css size is huge, you can use this method to downsize the codes so that visitors from slow internet connection can benefit from this optimization.

No comments:

Post a Comment