Tech Note: Minifying Javascript Quickly and Easily

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

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 [Link: <a href="http://www.crockford.com/javascript/jsmin.c" target="_blank">www.crockford.com...</a>]
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? 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

► 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.

You can't explain that.

TwitterFacebook
LGF Pages
Recent Pages

researchok
'I Was Looking Forward to a Quiet Old Age': Instead, Etta Shiber, Helped Smuggle Stranded Allied Soldiers To Freedom
3 hours, 30 minutes ago
Views: 53 • Comments: 0
Tweets: 1 • Rating: 0

Daniel Ballard
Late Afternoon Light-Kalanchoe
11 hours, 11 minutes ago
Views: 98 • Comments: 0
Tweets: 0 • Rating: 4

MikeySDCA
Colin Powell Endorsed Same-Sex Marriage Once It Was Safe, More Evidence He's Hardly a Great Leader.
11 hours, 15 minutes ago
Views: 124 • Comments: 1
Tweets: 0 • Rating: 1

Eclectic Infidel
City College of San Francisco Budget Update
12 hours, 3 minutes ago
Views: 113 • Comments: 0
Tweets: 0 • Rating: 0

Michael McBacon
Kansas governor signs 'Shariah bill' to ban Islamic law
16 hours, 34 minutes ago
Views: 224 • Comments: 6
Tweets: 0 • Rating: 5

Aigle
National Geographic Traveler Veers Off Track
1 day, 16 hours ago
Views: 447 • Comments: 7
Tweets: 0 • Rating: -5

MichaelJ
Apple TV Slated to Debut in December?
1 day, 17 hours ago
Views: 221 • Comments: 0
Tweets: 0 • Rating: 1

Ascher
Israeli Who Saved Turk on Everest: You Never Abandon a Friend - Israel News, Ynetnews
1 day, 19 hours ago
Views: 296 • Comments: 1
Tweets: 0 • Rating: 3

Haywood Jabloeme
The Harrassment of Patterico & Its Roots in Left-Wing Activism
1 day, 19 hours ago
Views: 516 • Comments: 2
Tweets: 0 • Rating: 4

Curt
Brian Banks: (Video) Falsely accused of rape speaks out
1 day, 21 hours ago
Views: 269 • Comments: 2
Tweets: 0 • Rating: 5

 Frank says:

Drop out of school before your mind rots from exposure to our mundane educational system. Forget about the Senior Prom and go to the library and *educate yourself* if you've got any guts. Some of you like *pep rallies* and plastic robots who tell you what to read. Forget I mentioned it. *This song has no message.* Rise for the flag salute. -- Liner notes for "Hungry Freaks, Daddy" on "Freak Out!"