When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Minify seems to be one of the easiest ways to shrink Javascript.
Turning on zip at the web server level can also help.
I'm surprised no one suggested gzipping your code. A straight ~50% saving there!
YUI Compressor does a pretty good job at compressing both Javascript and CSS.
I found JSCompress a nice way to not only minify a JavaScript, but to combine multiple scripts. Useful if you're only using the various scripts once. Saved 70% before compression (and something similar after compression too).
Remember to add back in any copyright notices afterwards.
Google hosts a handful of pre-compressed JavaScript library files that you can include in your own site. Not only does Google provide the bandwidth for this, but based on most browser's file caching algorithms, if the user has already downloaded the file from Google for another site they won't have to do it again for yours. A nice little bonus for some of the 90k+ JS libraries out there.
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:
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.