PHPSpeedy

There are 4 relatively easy ways by which you can speed up the time it takes a browser to download a page:

  • Make fewer HTTP requests
  • Add a far-future expires header
  • Gzip your page’s components
  • Minify your JavaScript, CSS and HTML

Following on from my post on joining CSS and JavaScript files, I have written a PHP script which will automatically do all of the above. All you have to do is call the following at the top of your page:

The code

PLAIN TEXT
PHP:

require_once(‘class.compressor.php’); //Include the class. The full path may be required
$compressor = new compressor(‘css,javascript,page’);

And the following at the bottom of the page:

PLAIN TEXT
PHP:

$compressor->finish();

The Demo

That’s it! Before I go into the details, the impatient amongst you can check out the test pages here:

The class can be downloaded here: site speed boost class download

Requirements

  • A server running at least PHP4. For JavaScript minification to work as well, PHP5+ is required.
  • You should set the folder where you are running the class from as writable

Setting basic options

Options can be set with a comma separated string as follows:

PLAIN TEXT
PHP:

$compressor = new compressor(‘css,javascript,page’);

The string can contain ‘css’, ‘javascript’ and ‘page’ depending on which elements you would like to be compressed. Any element contained in the string will be gzip encoded and minified.

Setting advanced options

Alternatively, an array can be passed to the class constructor with an advanced set of options. This array would set all the compression options to on:

PLAIN TEXT
PHP:

$compressor = new compressor(array(“javascript”=>array(“cachedir”=>’/minify’,
“gzip”=>true,
“minify”=>true,
),
“css”=>array(“cachedir”=>’/wp-content’,
“gzip”=>true,
“minify”=>true,
),
“page”=>array(“gzip”=>true,
“minify”=>true
)
));

You can change this array to add or remove all the available options.

Note that “cachedir” should not include a trailing slash. If your CSS files contain relative links for background images, you should set the CSS cachedir to the same directory the standard CSS files are stored in.

Speed gains

On my test page the load time with the compressor turned on was generally below second, and without the compressor between 3-5 seconds. The Yahoo Yslow rating went from F(45) to A(97).

Test page with Firebug, before compression

Firebug before compression

Test page with Firebug, after compression

Firebug before compression

Test page with Yslow, before compression

Firebug before compression

Test page with Yslow, after compression

Firebug before compression

Download

Please see the updated page

Credits

The JavaScript minification uses jsmin-php.