Javascript compression PHP class
Published Monday, January 21, 2008 in Javascript, PHP
In addition to my CSS compressor and constants parser I've also written a very simple Javascript compressor class that uses Nicolas Martin's PHP port of Dean Edward's Javascript packer.
It works in exactly the same way as the CSS-compressor. Create a new instance, pass the directory(ies) you want to look for .js-files in and then call the pack-method.
$jsc = new JSCompressor('js/');
echo $jsc->pack();
Reducing the number of HTTP requests the browser needs to make is essential for performance. Together with full packing of all the code, file-size is often reduced by up to 70% and the number of HTTP requests always down to 1.
Download the demo and have fun!






Comments
5 comments so far, why don't you post one too?
Saturday, March 29, 2008 | View all comments by Dirk Niemeier
Nice, I integrated this CSS and JS Compressor on my website to compress all files with one click. All files together have a filesize of 66 KB and the compressor reduces this size to 30 KB. It safes more than 50% on my site und it is very easy to use. It's just a pity that the JS compressor does not work with my AJAX files, AJAX requests won't work anymore. I have to find out the reason, perhaps I can solve the problem when I change some settings in the compression script.
Saturday, March 29, 2008 | View all comments by Dirk Niemeier
Okay, the problem was a missing ;. Up to now this error has not occured because the affected code passage is called not very often. Now the uncompressed code has a size of 120 KB and the compressed code has 55 KB - great!
Saturday, March 29, 2008 | View all comments by Andreas
@Dirk - Before compressing your JS you should run it through JSLint. JSLint checks for missing semicolons and such.
Also, all my JSCompressor does is fetch all the code in a directory, Dean Edwards JS-packer takes care of the rest.
Cheers for the comments.
Monday, May 04, 2009 | View all comments by marco
I had also built my own JS compressor for my AJAX-run site. However, there are some issues on the compressed JS file, most especially when the file is compressed as to just remove unnecessary spaces, comments and putting the code together in one single line. To make my compressed JS file error free I had to explicitly put the ; (semicolon) statement terminator on each line, even on function declarations which use var (like var foo=function(){...};).
Tuesday, May 05, 2009 | View all comments by Andreas
You should run your code through JSLint before compressing it to make sure it's error-free.