With Javascript becoming a large part of todays websites, the file sizes are beginning to get a bit scary. While it is true most clients will cache Javascript files, a user's first visit means downloading all of that code.
For example, using the
Prototype framework costs you about 55KB by default* (as of version 1.5.0rc0). If you want to use other libraries, then you're adding even more. The popular
script.aculo.us library, whcih lets you add stunning effects and controls to your pages, adds about 120KB by default**.
So it really is a good idea to compress the Javascript files you upload to your server. No one needs to read them or edit them, so you don't really loose anything.
Just two FYI's on the linked:
* The Prototype framework contains a lot of code you might not need. Try removing classes that you don't need. For example, if you don't use the AJAX class, then remove it.
** By default, when you include the main script.aculo.us script file into your page, it automatically loads the entire library for you. This might be good if you use everything the library has to offer, but if you only use one aspect, then it is a waste. For example, if you only use the effects then you don't want to include 80KB of extra JS you won't use. To remedy this problem, you can edit the main scriptaculous.js source file and modify the load() method to only load the files you need. Or simply include only the files you need and forget about the auto-loading.
Compressors
There are a number of JS compressors available. Many of them rely on complex regular expressions and tricks to squash everything. Sometimes they work, but often times they leave errors in their wake.
The one I like to use is the
Dojo Compressor. It does a more simplistic compression compared to some other compressors you might find on the market, but this one works and is totally free. Built on the Rhino Javascript engine from Mozilla, you can be sure your scripts will remain functional even after compression. You can download the JAR and run it locally on your machine, or you can use their online
ShrinkSafe application.
I created a batch file for use on my Windows machine that would compress all JS files in a directory and move the real source files into a new directory called '_src'. It's basic, but it works. If you want to write a better version, or want to write a bash script, reply and let the world benefit
Code:
@echo off
rename *.js *.real
for %%I in (*.real) do java -jar custom_rhino.jar -c %%I > %%~nI.js 2>&1
mkdir _src
move *.real _src
cd _src
rename *.real *.js
cd ..