views:

1805

answers:

16

When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?

+3  A: 

Minify seems to be one of the easiest ways to shrink Javascript.

Turning on zip at the web server level can also help.

Mark Biek
A: 

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.

nickf
+3  A: 

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.

Michael Haren
+2  A: 

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)

Sam Hasler
What's the issue when using packer and gzip together?
Andrew Hedges
see this answer: http://stackoverflow.com/questions/28932/best-javascript-compressor#28954
Sam Hasler
+1  A: 

Dojo Shrinksafe is a Javascript compressor that uses a real JS interpreter, so it won't break your code. The other ones can work well, but Shrinksafe is a good one to use in a build script, since you shouldn't have to re-test the compressed script.

+7  A: 

In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. you can always use tools like Dean Edward's Javascript Packer, but for css take the time to learn CSS Shorthand

background: #fff url(image.gif) no-repeat top left;

...instead of

background-color: #fff;
background-image: url(image.gif);
background-repeat: no-repeat;
background-position: top left;

use the cascading nature of css. for example if you know that your site will use one font-family define that for all elements that are in the body tag:

body{font-family:arial;}

one other thing that can help is including your css and javascript as files instead of inline or at the head of each page. That way your server only has to serve them once to the browser after that browser will go from cache.

Including Javascript

<script type="text/javascript" src="/scripts/loginChecker.js"></script>

Including CSS

<link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" />
Jim
+1  A: 

Shrinksafe may help: http://shrinksafe.dojotoolkit.org/ We're using it and it does a pretty good job. We execute it from an ant build for when packaging our web app.

Dustin
A: 

I'd give a test-drive to the new runtime optimizers in ASP.Net published on http://www.codeplex.com/NCOptimizer

+1  A: 

Helping the YUI Compressor gives some good advice on how you can tweak your scripts to achieve even better savings.

wrumsby
A: 

YUI Compressor does a pretty good job at compressing both Javascript and CSS.

Rexxars
A: 

YUI Compressor has my vote, for the simple reason that instead of just performing regular expression transformations on the code, it actually builds a parse tree of the code, similar to a Javascript interpreter, and then compresses it that way. It is usually very careful about how it handles the compression of identifiers.

Additionally it has a CSS compression mode, which I haven't played with as much.

Jonathan Arkell
A: 

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.

Eric DeLabar
+1  A: 

Compression and minify-ing (removing whitespace) are a start.

Additionally:

  1. Combine all of your JavaScript and CSS includes into a single file. That way the browser can download the source in a single request to server. Make this part of your build process.

  2. Turn caching on at the web-server level using the cache-control http header. Set the expiry to a large value (like a year) so the browser will only download the source once. To allow for future edits, include a version number on the query-string, like this:

<script src="my_js_file.js?1.2.0.1" type="text/javascript"></script>

<link rel="stylesheet" type="text/css" href="my_css_file.css?3.1.0.926" />

Dave Lockhart
+2  A: 

I'm surprised no one suggested gzipping your code. A straight ~50% saving there!

Rakesh Pai
A: 

CssTidy is the best CSS optimizer of which I am aware. It (configurably) strips comments, eliminates whitespaces, rewrites to use the many shorthand rules nickf mentioned, etc. Compressing the result helps too, as others have mentioned.

The compression ratio can be fairly dramatic, and it frees you to comment your CSS extensively without worrying about the file size.

Unfortunately, this level of preprocessing interacts with some of the popular "css hacks" in unpredictable (or predictable but undesired) ways. Some work, some don't, and some require configuration settings which reduce the level of compression for other things (especially comments).

Doug McClean
A: 

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.