Since I began using JQuery, my external Javascript files were getting HUGE. Using the following code, my external JS went from 108,499 to 34,066 bytes. My fairly small css file went from 6100 to 1600 bytes.

The following code is a modified version of Reinhold Weber’s PHP code. His code did not add compression; it only combined multiple css files into a single file. I basically added the expires header so the files are cached for one year, and the magical line: ob_start(“ob_gzhandler”);

The ob_gzhandler will automatically check to see if the client browser will accept gzip compression. If so, the file is sent compressed. This code should work with older browsers which do not accept compression, however is untested since I do not have any of the older browsers installed.

If you want to use this code for javascipt, you should create a separate file and change the 2nd line to: header(‘Content-type: text/javascript’);

Why two files? CSS should be called in the Head of the (x)html, and the scripts, toward the end of the (x)html. The only way I have been able to get the code to work is to call it from the html with:

<link rel=”stylesheet” href=”compress_css.php” type=”text/css” media=”screen” />

Compress_css.php

<?php
header('Content-type: text/css');

/* Expire one year from today's date */
$now = time( );
$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 365*86440);
header("Expires: $then");

ob_start("ob_gzhandler");

/* your css files */
include('allcss.css');

ob_end_flush();
?>

If you have multiple css or javascript files, you should be able to repeat the include(‘alljs.js’); with each javascript file and the script will combine them all. The following code will combine 1st_file.js and 2nd_file.js, compress them and send them out.

include(’1st_file.js’);
include(’2nd_file.js’);

Conclusion:

The code has been tested on a fairly large website with no problems. I have personally tested the code with all major browsers without a hitch.

GD Star Rating
loading...
Compress CSS and Javascript to Speed up your Webpage, 5.0 out of 5 based on 1 rating