LGF

more options

  

Advertisement

Tech Note: Minifying Javascript Quickly and Easily

Sun, Aug 3, 2008 at 4:01:24 pm PDT

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();}elsesomethingelse();

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

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

Advertisement

64 comments

  • Comments are open and unmoderated, and do not necessarily reflect the views of Little Green Footballs.
  • Obscene, abusive, silly, or annoying remarks may be deleted, but the fact that particular comments remain on the site in no way constitutes an endorsement of their views by Little Green Footballs.
  • Posts that contain phone numbers, street addresses, email addresses or other personal information will also be deleted, as will posts that consist only of a variation on the word, "First!"
  • Comments that advocate violence will be cause for immediate banning with no appeal.
  • Disagreement and debate are welcome, but insults and abuse are not, and may cause your account to be blocked.
  • REMEMBER: posting comments at LGF is a privilege, not a right. Abuse that privilege, and your account will be blocked.

Hide comments | Jump to bottom

1 simonml  Sun, Aug 3, 2008 4:03:43pm

You are so much smarter than I. For that I thank you. Keep up the great work!

2 vxbush  Sun, Aug 3, 2008 4:04:35pm

Schweet. Unfortunately, I'm just not a Javascript person.

3 twincitiesgirl  Sun, Aug 3, 2008 4:06:10pm

you are quite the amazing man Charles.

/really

4 M. Bensson-Levi  Sun, Aug 3, 2008 4:06:16pm

A tech thread? I come from that branch of the human family that accepted fire only three generations ago.

5 mossley  Sun, Aug 3, 2008 4:06:21pm

Neat. I don't have a use for it at the moment, but it's something that might come in handy later.

6 Mike in Georgia  Sun, Aug 3, 2008 4:09:26pm

I get my java from Dunkin Donuts every morning.

7 zombie  Sun, Aug 3, 2008 4:10:07pm

Gjauskss lajdpp bpjahms asjsvsnk sjh akjckjs!

/That makes more sense to me that what Charles wrote, at least.

8 zombie  Sun, Aug 3, 2008 4:11:08pm

re: #4 M. Bensson-Levi

I come from that branch of the human family that accepted fire only three generations ago.

But where are the transitional heating methods?

9 Tigger2005  Sun, Aug 3, 2008 4:12:29pm

Ok, now who wants to talk about the Java, er, Jihad?

10 pre-Boomer Marine brat  Sun, Aug 3, 2008 4:13:49pm

My brain is now minifried.
*fumbling for the coffee pot*

(seriously)

Charles,

I have far fewer problems at LGF than on any other website -- with the exception of Google Search, which, I suspect, is a cached "gimme" anyway.

You do a damned fine job here!

/signed
Gray-headed circuit-level hardware guy who HATES cheezy software

11 Attaboid  Sun, Aug 3, 2008 4:14:46pm

Long live C.

12 pre-Boomer Marine brat  Sun, Aug 3, 2008 4:15:15pm

re: #7 zombie

Gjauskss lajdpp bpjahms asjsvsnk sjh akjckjs!

/That makes more sense to me that what Charles wrote, at least.

Uh ... did you mean to put that in the future tense?

13 Tigger2005  Sun, Aug 3, 2008 4:15:28pm

re: #3 twincitiesgirl

you are quite the amazing man Charles.

/really

His code is so hot!

14 Tigger2005  Sun, Aug 3, 2008 4:18:08pm

Langly: Say it...say it.
Frohike: Your kung-fu is the best.

15 doriangrey  Sun, Aug 3, 2008 4:19:06pm

re: #14 Tigger2005

Langly: Say it...say it.
Frohike: Your kung-fu is the best.

The truth is out there....

16 twincitiesgirl  Sun, Aug 3, 2008 4:22:52pm

re: #13 Tigger2005

so true!

17 The Other Les  Sun, Aug 3, 2008 4:25:44pm

I have to wonder sometimes at the sheer asininity of the self appointed superior being.

One of them defaced Wikipedia's page on the subject of the jucy lucy. (I usually get them where Juicy is spelled correctly.)

[Link: www.thedeets.com...]

Two dry hamburger patty halves sealed together with a slice of moldy cheese in between, cooked up on some South Minneapolis two bit bar's greasy unclean grill and served to unsuspecting tourists who expect higher levels of cleanliness and food freshness than is available in Minnesota. Locals, whose stomachs are accustomed to such moldy, bacteria laden fare consider Jucy Lucy's a rare local delicacy. Buyer beware: its hard enough to properly and thoroughly cook hamburger. Try properly cooking it with a melting piece of cheese stuffed between the sealed together patties.

Feh!

18 uncleFuzzy  Sun, Aug 3, 2008 4:29:43pm

Here's a (slightly) Tech Note and admittedly un-related.

Brian May from Queen has put his PhD. thesis on Amazon.

19 realwest  Sun, Aug 3, 2008 4:30:49pm

I'm not feeling well so maybe that's why I don't understand what the heck Charles has said up above.
Is there anything I have to do to keep using LGF? Any settings I have to change?

20 Killgore Trout  Sun, Aug 3, 2008 4:31:25pm

WorldNutDaily is at it again....
Darwin's deadly delusions

21 M. Bensson-Levi  Sun, Aug 3, 2008 4:31:40pm

re: #8 zombie

But where are the transitional heating methods?

Body warmth! I've heard that a steak, under the arm pit for 8 hours was sort of gross, but hey, I'm 3 generations removed from that. I accept fire!

Flight, on the other hand...

22 Killgore Trout  Sun, Aug 3, 2008 4:31:56pm

re: #19 realwest

Just kick back and enjoy the goodness.

23 Truck Monkey  Sun, Aug 3, 2008 4:32:38pm

I'll take your word for it.

24 goddessoftheclassroom  Sun, Aug 3, 2008 4:34:50pm

re: #19 realwest

I'm not feeling well so maybe that's why I don't understand what the heck Charles has said up above.
Is there anything I have to do to keep using LGF? Any settings I have to change?

{realwest}

I hope you're better soon.

25 Russkilitlover  Sun, Aug 3, 2008 4:35:06pm

OT and certainly not tech related - Alexander Solzhenitsyn has died. Although the Gulag Archipelago is considered his masterpiece, I much prefer his 1914-1918 series. A good dissident against the soviet regime, but not much of a fan of democracy, either. He was a true socialist. In any case, an important writer is lost, but his works are not.

26 LEGION  Sun, Aug 3, 2008 4:35:09pm

Yadda yadda yadda blim bloom blam We should take obama and drop him on Iran.

27 OldLineTexan  Sun, Aug 3, 2008 4:35:32pm

Well, we are only a few dozens or hundreds of generations away from having to build a hut every time we wanted to roast a pig.

/old moldy joke

28 realwest  Sun, Aug 3, 2008 4:35:47pm

re: #22 Killgore Trout
Oh, thanks Killgore, but I'm really effin' sick - from a lot of different things I think - I think the tooth that won't get pulled for 3 weeks may be infected, stomach is bothering me yada yada yada.
I just was checking LGF and wanted to make sure I was cool here - seemed like Charles was saying techie stuff, techie stuff and then:
"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."
Glad Charles is such a genius and even more glad that I can be the dolt I am and still enjoy LGF.

29 OldLineTexan  Sun, Aug 3, 2008 4:36:21pm

re: #25 Russkilitlover

Good grief...how old was he? I remember when the Gulag Archipelago book was everywhere...

30 goddessoftheclassroom  Sun, Aug 3, 2008 4:37:05pm

re: #25 Russkilitlover

OT and certainly not tech related - Alexander Solzhenitsyn has died. Although the Gulag Archipelago is considered his masterpiece, I much prefer his 1914-1918 series. A good dissident against the soviet regime, but not much of a fan of democracy, either. He was a true socialist. In any case, an important writer is lost, but his works are not.

I used to teach his short story, "One Day in the Life of Ivan Denisovich."

31 LEGION  Sun, Aug 3, 2008 4:37:08pm

re: #29 OldLineTexan

I remember hearing about him in the 70's- so he just died? Ho hum.

32 Killgore Trout  Sun, Aug 3, 2008 4:38:17pm

re: #28 realwest

Hang in there, bud.

33 LEGION  Sun, Aug 3, 2008 4:38:28pm

Alexander Solzhenitsyn, the Nobel Prize-winning Russian author whose books chronicled the horrors of dictator Josef Stalin's slave labor camps, has died of heart failure, his son said Monday. He was 89.

Wow- not that old.

34 Russkilitlover  Sun, Aug 3, 2008 4:38:45pm

re: #28 realwest

{realwest} Nothing seems more unfair than feeling crappy in glorious summer. Do you have a lot of homemade chicken soup? Really helps the immune system - not just an old wives' tale - seems to have a lot of healing properties. Also, parsley juice. Sounds weird, but my eastern European foremothers swore by it.

35 Russkilitlover  Sun, Aug 3, 2008 4:40:24pm

re: #30 goddessoftheclassroom

I used to teach his short story, "One Day in the Life of Ivan Denisovich."

I dissected that one in high school, as well. Is it still taught? Unfortunately, his other works are so much more "important" but it's hard to wade through his ponderous prose.

36 realwest  Sun, Aug 3, 2008 4:41:57pm

re: #32 Killgore Trout
Thanks Killgore. I appreciate it.

37 Russkilitlover  Sun, Aug 3, 2008 4:42:33pm

re: #31 LEGION

I remember hearing about him in the 70's- so he just died? Ho hum.

Ho hum? Pick up some of his work. Should be part of everyone's literary repertoire.

38 realwest  Sun, Aug 3, 2008 4:42:57pm

re: #34 Russkilitlover
Thanks but the last thing I want to do is eat something and unfortunately my cancer has compromised my immune system pretty damn well now - but I do appreciate the kind thoughts.

39 realwest  Sun, Aug 3, 2008 4:43:38pm

Anyway I gotta go now - I really hope I get the chance to see all y'all down the road.

40 OldLineTexan  Sun, Aug 3, 2008 4:44:08pm

re: #39 realwest

Hope to see you later. Take care, bud.

41 LEGION  Sun, Aug 3, 2008 4:45:41pm

re: #35 Russkilitlover

Like you said, "it's hard to wade through his ponderous prose."

42 fish-man  Sun, Aug 3, 2008 4:46:02pm

Duuuude, this takes me way back to compressing code for code interpreters in the 70s and 80s. Remember writing code when the size it took up mattered? Bitmapping? And Overlay Description Language! Duuuuude! I wonder if ODL might come back too! My wild coding skillz might be useful again!

43 LEGION  Sun, Aug 3, 2008 4:51:46pm

[Link: news.yahoo.com...]

After a triumphant return from exile in the U.S. in 1994 that included a 56-day train trip across Russia to become reacquainted with his native land, Solzhenitsyn later expressed annoyance and disappointment that most Russians hadn't read his books.

Solzhenitsyn then made his homeland in America, settling in 1976 in the tiny town of Cavendish, Vermont, with his wife and sons.

Living at a secluded hillside compound he rarely left, he called his 18 years there the most productive of his life. There he worked on what he considered to be his life's work, a multivolume saga of Russian history titled "The Red Wheel."
Some critics saw "The Red Wheel" books as tedious and hectoring, rather than as sweeping and lit by moral fire.
Although free from repression, Solzhenitsyn longed for his native land. Neither was he enchanted by Western democracy, with its emphasis on individual freedom.
To the dismay of his supporters, in his Harvard speech he rejected the West's faith "Western pluralistic democracy" as the model for all other nations. It was a mistake, he warned, for Western societies to regard the failure of the rest of the world to adopt the democratic model as a product of "wicked governments or by heavy crises or by their own barbarity or incomprehension."

"Exile from his great theme, Stalinism and the gulag, had exposed his major weaknesses," D.M. Thomas wrote in a 1998 biography, theorizing that the intensity of the earlier works was "a projection of his own repressed violence."

44 Russkilitlover  Sun, Aug 3, 2008 4:53:10pm

re: #41 LEGION

Like you said, "it's hard to wade through his ponderous prose."

I look on it as akin to weight lifting. I hate weights - much prefer swimming, spinning, and aerobics, but the weights built muscle.

Solzhenitsyn is definitely weight lifting, metaphoric and realistic - try lifting one of his hardbacks!

45 lawhawk  Sun, Aug 3, 2008 4:58:22pm

re: #33 LEGION

Alexander Solzhenitsyn, the Nobel Prize-winning Russian author whose books chronicled the horrors of dictator Josef Stalin's slave labor camps, has died of heart failure, his son said Monday. He was 89.

Wow- not that old.

Amazing he lived that long given what he lived through.

46 M. Bensson-Levi  Sun, Aug 3, 2008 5:03:17pm

re: #30 goddessoftheclassroom

I used to teach his short story, "One Day in the Life of Ivan Denisovich."

What a great tale! You're very fortunate. You dwell in the land of literature, the garden of the mind. Few are so blessed. I know that you very much appreciate your special status, and privilege.

All honor to you. Kol HaKavod.

Keep, and teach, the Faith. I am absolutely secular in this statement, as I am sure you appreciate.

Continue to do good. It is teachers like you, that made me strive, and accomplish, and I ain't no slouch! I've done a good sight more than most, thanks to teachers like you.

G-d bless you.

Now, as I recall, have you seen the 1968 Dudley Moore/Peter Cook version of "BEDAZZLED"? If not, hesitate no longer. You'll love, and appreciate it.

Thank me later.

47 Noam Sayin'  Sun, Aug 3, 2008 5:04:14pm

re: #45 lawhawk

Page not found
Sorry, the page you were looking for in the blog A Blog For All does not exist.

48 lori lane  Sun, Aug 3, 2008 5:11:18pm

re: #39 realwest

{realwest} Hey, please see a doc about the possible infection. You might need some antibiotics! :(

49 lawhawk  Sun, Aug 3, 2008 5:11:23pm

re: #47 Noam Sayin'

Crap.. Kludged the link. Here it is.

50 stevieray  Sun, Aug 3, 2008 5:21:45pm

Hmmm...

Under the "Now Playing" widget... when did the "Recently Played" link show up?

51 DoubleU  Sun, Aug 3, 2008 5:29:47pm

And how do you grab the information from Amazon from the Now Playing widget?

52 debutaunt  Sun, Aug 3, 2008 5:49:26pm

re: #28 realwest

Oh, thanks Killgore, but I'm really effin' sick - from a lot of different things I think - I think the tooth that won't get pulled for 3 weeks may be infected, stomach is bothering me yada yada yada.
I just was checking LGF and wanted to make sure I was cool here - seemed like Charles was saying techie stuff, techie stuff and then:
"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."
Glad Charles is such a genius and even more glad that I can be the dolt I am and still enjoy LGF.

Would antibiotics interfere with you other meds?

53 kc_kunz  Sun, Aug 3, 2008 7:49:26pm

How well does this interact with the No-script plugin for firefox?

if you minify a batch of scripts and have one that is not permitted by No-Script, will all of your scripts be blocked? Right now No-script is showing 3 scripts for this page, one of the three is explicitly trusted, the other two are temporarily trusted.

54 just another four-letter word  Sun, Aug 3, 2008 7:58:55pm

re: #10 pre-Boomer Marine brat

My brain is now minifried.
*fumbling for the coffee pot*

(seriously)

Charles,

I have far fewer problems at LGF than on any other website -- with the exception of Google Search, which, I suspect, is a cached "gimme" anyway.

You do a damned fine job here!

/signed
Gray-headed circuit-level hardware guy who HATES cheezy software

...and as another grey-headed circuits guy and RTOS programmer (if you can't program in machine language you CAN'T PROGRAM!), anything that minimizes code is a Real Good Thing. Thanks for helping the newbies along, Charles!

JAFLW

55 rickadams  Sun, Aug 3, 2008 8:03:48pm

Compiles and runs great under Cygwin, too.

56 suboptimal  Sun, Aug 3, 2008 8:23:54pm

Very cool. Completely useless for me, but very cool indeed.

57 alpine lizard  Sun, Aug 3, 2008 8:27:21pm

re: #53 kc_kunz

How well does this interact with the No-script plugin for firefox?

It should be transparent. JSMIN just reformats the the Javascript source code. The resulting code should be understood by NoScript as well as the original source.

... Right now No-script is showing 3 scripts for this page, one of the three is explicitly trusted, the other two are temporarily trusted.

NoScript blocks scripts based on their location. JSMIN doesn't change anything here, either.

58 big L  Sun, Aug 3, 2008 8:45:01pm

IT looks like stanzas of music. I'm glad you share these sectons with us. That way we can learn.

Take care realwest. I'll be thinking of ya, good thoughts, well thoughts.

59 Lee Coller  Sun, Aug 3, 2008 9:43:44pm

re: #11 Attaboid

Long live C.

C is OK, C++ is better.

60 clgood  Sun, Aug 3, 2008 10:42:20pm

Charles:

Since you're getting into shell script automation, have you learned the wonders of "make"? You could write a Makefile that wraps all this up in a very slick way if you want. It would know when your source files have changed and just re-minify and concatinate the pieces that need it.

61 Pooncakes, Hero of Zion  Mon, Aug 4, 2008 3:07:34am

Why not do it in assembly?

62 just another four-letter word  Mon, Aug 4, 2008 7:19:38am

re: #61 Pooncakes, Hero of Zion

Why not do it in assembly?

Well, except for real-time ("When it absolutely, positively has to be done in 40 microseconds or less!"), assembly language is cumbersome and very difficult to debug. It's not for the faint of heart and those of you that need to get the coding done quickly. Having lived in the RTOS and OOP (THERE's a bridge for ya!) worlds, having a higher-level language keeps things less mundane ("where, oh where in memory did I put that result/variable/table ?") and easier to fix. And easier to read!

Given a choice, higher-level languages are the way to go. Trust me.

JAFLW

63 justadot  Mon, Aug 4, 2008 10:01:59pm
cat my.js ¦ jsmin > my.min.js

—uuoca!
jsmin < my.js > my.min.js

Just kiddin', boss.
Easy instructions, quick download, trouble-free compilation, useful application.
Thanks again, Charles.

64 Charles  Tue, Aug 5, 2008 8:03:33am

re: #63 justadot

—uuoca!
jsmin < my.js > my.min.js

Just kiddin', boss.
Easy instructions, quick download, trouble-free compilation, useful application.
Thanks again, Charles.

Yes, you could do it that way too.


This entry has been archived.
Comments are closed.

^ back to top ^

log in
Name:
Pass:

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

► LGF Headlines

► Top 10 Comments

► Bottom Comments

► Recent Comments

► Tools/Info

► LGF Hits

► Slideshows

► 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

► News/Opinion

20% off Easy Reading Programs and More at Hooked On Phonics
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.

Your pilikia is all pau.


Save $5 off $50 at Kmart with code KMART5OFF50