Speeding Up Your PHP Web Site
Minify Your CSS, JavaScript and HTML
An extremely effective way to decrease the amount of traffic being sent is to make your JavaScript and CSS files smaller. One way to do this is to use Yahoo!'s YUI Compressor.Although this is a Java library, it is easy to leverage it from within PHP. All you need is Java installed (which most servers do) and the
yuicompressor.jar
file.
The following code shows a basic implementation of using YUI Compressor to serve minified JavaScript.
Listing 1 Compressing JavaScript and CSS with YUI Compressor (listing-1.php)
$java = '/usr/bin/java'; $yui = '/path/to/yuicompressor.jar'; $file = '/path/to/script.js'; $cmd = sprintf( '%s -jar %s --type js %s', escapeshellcmd($java), escapeshellarg($yui), escapeshellarg($file) ); $output = trim(`$cmd`); header('Content-type: text/javascript'); header('Content-length: ' . strlen($output)); echo $output;
When using YUI Compressor, you can either specify the content type (either
js
or css
), or it will auto-detect based on the input filename.
You can achieve similar results for your HTML files using the htmlcompressor tool. Once again, this is a Java library. This library will automatically use YUI Compressor if you use it for CSS or JavaScript (as long as
yuicompressor.jar
is present in the same directory as htmlcompressor.jar
).
No comments:
Post a Comment