When working with large and/or many Javascript and CSS files, what\'s the best way to reduce the file sizes?
See the question: Best javascript compressor
Depending on whether or not you are going to gzip your JavaScript files may change your choice of compressor. (Currently Packer isn't the best choice if you are also going to gzip, but see the above question for the current best answer)
For javascript, I use Dean Edwards's Javascript Packer. It's been ported to .NET, perl, php4, php5, WSH, and there's even an aptana plugin.
Javascript packing comes in a few flavours - some just strip out comments and whitespace, others will change your variable names to be concise, and others, well, I don't even know what they do, but the output sure is small. The high-end compression works by using the eval() function, which puts some extra burden on the client, so if your scripts are particularly complicated, or you're designing for slower hardware, keep that in mind. the Javascript packer gives you the option for which compression level you want to use.
For CSS, the best you can do is strip whitespace and comments. Thankfully that means that you can achieve that with a one-line function:
function compressCSS($css) {
return
preg_replace(
array('@\s\s+@','@(\w+:)\s*([\w\s,#]+;?)@'),
array(' ','$1$2'),
str_replace(
array("\r","\n","\t",' {','} ',';}'),
array('','','','{','}','}'),
preg_replace('@/\*[^*]*\*+([^/][^*]*\*+)*/@', '', $css)
)
)
;
}
While that function and the Javascript packer will reduce the file size of individual files, to get the best performance from your site, you'll also want to be reducing the number of HTTP requests you make. Each Javascript and CSS file is a separate request, so combining them into one file each will the the optimal result. Instead of trying to maintain a single bohemoth JS file, you can use the program/technique I've written on my blog (shameless self plug) at http://spadgos.com/?p=32
The program basically reads a "build script"-type file which will simultaneously combine and compress multiple Javascript and CSS files into one (of each) for you (or more, if you want). There are several options for the output and display of all files. There's a larger write-up there, and the source is freely available.
I'm surprised no one suggested gzipping your code. A straight ~50% saving there!
Minify seems to be one of the easiest ways to shrink Javascript.
Turning on zip at the web server level can also help.
Rather than tweaking your files directly, I would recommend compressing them. Most clients support it.
I think you'll find that this is easier and just as effective.
More details from Jeff's adventures with it.
Try web compressor tools from Boryi to compress your standard HTML file (without Javascript code and css code embedded, but can be linked to or imported), Javascript code (properly ended with ;), and css code.