Tech Note: Minifying Javascript Quickly and Easily

Charles Johnsonfollow me on twitter
Sun Aug 3, 2008 at 4:01 pm PDT • Views: 414

A technique I use at LGF to speed up the loading of Javascript files is to run them through a “minifier” script that removes spaces and extraneous formatting such as comments. Combined with server-side gzip compression, this produces the smallest possible download size. (There’s another technique for compressing Javascript called “packing” that results in smaller JS files — but they don’t compress as well with gzip.)

So here’s a method to semi-automate the “minifying” process, assuming you have root (or sudo) access to your web server and some experience with Linux commands and simple shell scripting. This method is cool because it lets you keep both original and compressed copies of your Javascript easily accessible on the server, and quickly generate the minified versions whenever you make a change.

The first step is to download the C source code for the Javascript minimizer by Douglas Crockford, available here: JSMIN, The JavaScript Minifier. (Scroll to the bottom of the page for the link to the C source.)

We’ll log in with SSH, change to the directory where we’re going to put the minifier, then use the wget command to get the C source code directly from crockford.com. Then we’ll compile the C code into a small executable file named jsmin.

cd /usr/local/me
wget http://www.crockford.com/javascript/jsmin.c
gcc -o jsmin ./jsmin.c

You now have a Linux command that takes Javascript code from standard input, minifies it, and sends the result to standard output. Assuming you’ve properly edited the include paths in your bash login scripts (which is a bit beyond the scope of this little tech note), you should be able to call the command from anywhere.

Now we’re set up. If you’ve just edited a Javascript file and you want to minify it, here’s how: log in, navigate to the directory where your edited file is located, and use the following command line to pipe the original Javascript file through jsmin and write out the compressed code to a new file.

cat my.js | jsmin > my.min.js

To get even trickier, put these commands in a shell script that calls jsmin repeatedly to add a series of Javascript files to one “master” minified file, like this:

#!/bin/bash
cd /path/to/site/js/
cat my.js | /usr/local/me/jsmin > my.min.js
cat my.extra1.js | /usr/local/me/jsmin >> my.min.js
cat my.extra2.js | /usr/local/me/jsmin >> my.min.js

I use this technique to combine several jQuery plugins into one minified file.

If you saved this shell script with a name like minify, you could make changes in a series of Javascript files, save or upload them, then just type:

minify

...and all your Javascript code would be minified and concatenated into one file, for the smallest possible download. And the compiled C version of jsmin is exceedingly fast.

UPDATE at 8/5/08 3:28:32 pm:

To squeeze a few more bytes out of the minified code, you can also try stripping out line breaks by piping jsmin’s output through the tr command:

cat my.js | jsmin | tr -d "\n" > my.min.js

Some poorly-formed Javascript code breaks when you strip out newlines, however. Here’s an example of one bit of code I’ve encountered that needs a newline to work properly:

if (variable) {
    dosomething();
} else
    somethingelse();

Technically, this is not illegal code, but it relies on the newline to provide space between the else statement and the call to somethingelse(). When you strip newlines, the code ends up like this:

if(variable){dosomething();}<strong>elsesomethingelse</strong>();

A better way is to add the technically unnecessary set of braces around the else condition:

if (variable) {
    dosomething();
} else {
    somethingelse();
}
Advertisement

64 comments

^ back to top ^

Name:

Pass:

Register Forgot Your Password? Account Settings Re-send Confirmation (To log in, cookies must be enabled in your browser!)

Turn off ads by subscribing!
For about 33 cents a day, our subscription option turns off all advertisements at LGF!
Read more...


► LGF Headlines

  • Loading...

► Tweeted Articles

  • Loading...

► Tweeted Pages

  • Loading...

► Top 10 Comments

  • Loading...

► Bottom Comments

  • Loading...

► Recent Comments

  • Loading...

► Tools/Info

► LGF Hits

► Resources

► Never Forget

► Statistics

► Tag Cloud

► Contact

You must have Javascript enabled to use the contact form.
Your email:

Subject:

Message:


Messages may be published in our weblog, unless you request otherwise.
Tech Note:
Using the Contact Form

More Partners

Compare Electricity Prices in your area. Texas Electricity is deregulated; you have the right to choose Texas Electric Rates from among many Texas Electric Companies.

Remember it's still a believe system.

TwitterFacebook
LGF Pages
Recent Pages

Look At My New Grandbaby!
Landmark Restaurant Settles With Customer who Received Racist Receipts
5 minutes ago
Views: 19 • Comments: 0
Tweets: 0 • Rating: 0

researchok
Amnesty International Report Brands Libya's Militias 'Out of Control'
11 minutes ago
Views: 14 • Comments: 0
Tweets: 0 • Rating: 0

Channeling Confucius
You should soon be getting fewer of those annoying 'robocalls' at home.
13 minutes ago
Views: 7 • Comments: 0
Tweets: 0 • Rating: 0

researchok
Crime Stoppers Buys Plots So Josh Powell Can't Be Buried Next to Sons
14 minutes ago
Views: 13 • Comments: 0
Tweets: 0 • Rating: 0

jaunte
The Right-Wing Media's Discipline Machine
1 hour, 35 minutes ago
Views: 84 • Comments: 0
Tweets: 1 • Rating: 1

Look At My New Grandbaby!
Mitt Romney Tells Detroit to Drop Dead
1 hour, 45 minutes ago
Views: 98 • Comments: 0
Tweets: 3 • Rating: 2

Channeling Confucius
Haitian Invasion Welcomed in Rural America - BBC Video
2 hours, 16 minutes ago
Views: 49 • Comments: 0
Tweets: 0 • Rating: 0

MichaelJ
Samsung's Galaxy Note Is the Most Useless Phone I've Used
2 hours, 17 minutes ago
Views: 85 • Comments: 2
Tweets: 0 • Rating: 0

Randall Gross
GM Moves From Pension Plan to 401(k) - Feb. 15, 2012
2 hours, 21 minutes ago
Views: 54 • Comments: 2
Tweets: 0 • Rating: 1

Randall Gross
Religion Over Rights? Kansas Bill Would Let 'Religious Freedom' Curb Civil Liberties
2 hours, 22 minutes ago
Views: 123 • Comments: 2
Tweets: 0 • Rating: 4

 Frank says:

Don't clap for destroying America. This place is as good as you want to make it. -- Zappa introduced "Billy the Mountain" by revealing that Billy and Ethel took a vacation trip across the United States, destroying it in the process. This was Zappa's response to the applause and cheers from the audience. Cleveland Colliseum, 1971