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):


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


// 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");



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.

1 comment:

  1. Your good knowledge and kindness in playing with all the pieces were
    very useful. I don’t know what I would have done if I had not
    encountered such a step like this.

    white label website builder