TwitterFacebook

Minifying Javascript With the Google Closure Compiler API

Honey, I shrunk the codes
LGF • Views: 35,857
Javascript via Shutterstock

The dirty secret of these tech posts is that I often write them for myself, because they help me organize my thoughts; sometimes the process of making it simple enough and abstract enough to post about on LGF even suggests improvements to programming techniques.

And believe it or not I got an email today from someone saying they wished I’d do more of them. So that’s pretty much all the excuse I need to launch into another tech/programming article that can be treated as an open thread by the non-programmers amongst us.

A while back I wrote an article titled Tech Note: Minifying Javascript Quickly and Easily, about the method I used to compress and “minify” our Javascript files before sending them out over the interwebs.

This method has evolved quite a bit, and now LGF uses the Google Closure Compiler to perform this compression, because it does a vastly better job than the outdated minifier we were using, and also has some simple syntax checking.

If the old minifier failed in some way, it used to happily create a bad Javascript file, and you found out when you loaded the page and there was no Javascript working at all. The Closure Compiler exits gracefully with an error, a line number, and a useful message about why it failed.

There are several ways to use the Closure Compiler — as a simple web application, as a Java application that you install on a server, or as a web API using the REST protocol. This bit of nerd doggerel I’m about to foist on you shows how to use the RESTful API to generate a minified version of one Javascript file, with a Linux bash script that you execute on your server after making changes to the Javascript code.

This code sends the web URL of a Javascript file to the Closure compiler, then saves the returned minified code on your server and moves it into place with a safe rename command, so no one gets caught loading it in mid-change.

The paths and filenames are generalized here — if you use the code, fill in the proper values, then save it wherever you put your bash scripts and give it executable permissions. I use the command name lgfj for our version at LGF, to make typing easy.

To start with, we set the working directory to the path where our Javascript files are located and print out a warm, fuzzy welcome message.

#!/bin/bash

cd /path/to/javascript/files/

echo -e "\nJavascript Minifier (API version)\n"
echo "Minifying test.js with Closure Compiler..."

In order to pass the web address of a Javascript file to the Closure Compiler’s API, we need to “URL-encode” it, which means to replace some characters with special codes. We’ll use Perl’s URI::Escape module for this.

And there’s a lurking gotcha that I discovered when first working with this script: Google’s API can’t always tell when you’ve changed the code, and will use a cached version to speed things up. Since we’re only running this after we’ve made a change, we never want this behavior. So we use a simple method to force Google not to cache the file: we append the Linux date value to the Javascript file’s URL as a query string. Since this value increases every second, it changes every time we use it — so our Javascript file will always look like a different file to Google.

All this happens in the following somewhat gnarly looking line of code. The result is stored in the variable $URL.

URL=$(echo "http://yourdomain.com/js/test.js?"$(date +%s) | perl -MURI::Escape -lne 'print uri_escape($_)')

OK, now we do the actual deed and call the Closure Compiler’s API, by using Linux’s curl command with the -d flag that tells it to use the POST method. See the docs for more info on the parameters in the query string.

The resulting minified code is then written out to the file test.min.tmp.js.

curl -d "output_info=compiled_code&output_format=text&compilation_level=SIMPLE_OPTIMIZATIONS&code_url=$URL" 'http://closure-compiler.appspot.com/compile' > test.min.tmp.js

Now we set the file’s owner to whatever is appropriate, and safely move the minified file into place by renaming test.min.tmp.js to test.min.js.

echo "Creating lgf.min.js..."

chown username test.min.tmp.js
mv -f test.min.tmp.js test.min.js

echo "Completed."

Done! But let’s also share some information about what just happened. These concluding lines show the file sizes of the original Javascript file and the minified version, and the amount saved by the minification process.

OSIZE=$(stat -c%s test.js)
MSIZE=$(stat -c%s test.min.js)
echo -e "Original size: "$(printf "%'d\n" $OSIZE)" bytes"
echo -e "Minified size: "$(printf "%'d\n" $MSIZE)" bytes"
echo -e "Saved:         "$(printf "%'d\n" $(($OSIZE - $MSIZE)))" bytes\n"

Here’s the whole thing in one piece:

#!/bin/bash

cd /path/to/javascript/files/

echo -e "\nJavascript Minifier (API version)\n"
echo "Minifying test.js with Closure Compiler..."

URL=$(echo "http://yourdomain.com/js/test.js?"$(date +%s) | perl -MURI::Escape -lne 'print uri_escape($_)')

curl -d "output_info=compiled_code&output_format=text&compilation_level=SIMPLE_OPTIMIZATIONS&code_url=$URL" 'http://closure-compiler.appspot.com/compile' > test.min.tmp.js

echo "Creating lgf.min.js..."

chown username test.min.tmp.js
mv -f test.min.tmp.js test.min.js

echo "Completed."

OSIZE=$(stat -c%s test.js)
MSIZE=$(stat -c%s test.min.js)
echo -e "Original size: "$(printf "%'d\n" $OSIZE)" bytes"
echo -e "Minified size: "$(printf "%'d\n" $MSIZE)" bytes"
echo -e "Saved:         "$(printf "%'d\n" $(($OSIZE - $MSIZE)))" bytes\n"

You can also use the Closure Compiler API to compress and combine a series of Javascript files into one big file, which can save even more loading time, but that’s a subject for another nerdy nerd thread.

^ back to top ^

TwitterFacebook

Turn off all ads for a full year by subscribing!
For about 33 cents a day (per month) or 22 cents a day (per year), 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 unless you request otherwise.
Tech Note:
Using the Contact Form
LGF Pages

This button leads to the main index of LGF Pages, our user-submitted articles. You can post your own LGF Pages simply by registering a free account with us.

Create a Page

This is the LGF Pages posting bookmarklet. To use it, drag this button to your browser's bookmark bar, and title it 'LGF Pages' (or whatever you like). Then browse to a site you want to post, select some text on the page to use for a quote, click the bookmarklet, and the Pages posting window will appear with the title, text, and any embedded video or audio files already filled in, ready to go.

Last updated: 2014-03-07 2:19 pm PST

LGF User's Guide
Recent Pages
team_fukit
Zimmerman Divorce Affidavit: Spends $3300 a Month, Makes $0
Where did all the fine art money he made go? George Zimmerman divorce records: I've got no home, no job and spend $100 a month on vacationsby Rene Stutzman SANFORD - George Zimmerman has no job, no home, no income ...

1 hour, 13 minutes ago
Views: 66 • Comments: 1
Tweets: 0 • Rating: 0
Randall Gross
Militia Efforts to Converge at the Border Fizzle Out
What if militias announced a showdown with the feds and nobody came? That's pretty much what happened in Texas this week, after a handful of militia activists called on their fellow militia members to intervene in the increasingly fraught ...

4 hours, 27 minutes ago
Views: 165 • Comments: 1
Tweets: 14 • Rating: 2
FemNaziBitch
War in the West: The Bundy Ranch Standoff and the American Radical Right
Since 2009, there have been 17 shooting incidents between antigovernment extremists and law enforcement. In 2010, a father-and-son team of sovereign citizens, who believe that the law doesn't apply to them, executed two Arkansas police officers during a traffic ...

5 hours, 2 minutes ago
Views: 198 • Comments: 0
Tweets: 35 • Rating: 1
Skip Intro
Why Obama Must Go to the Border Immediately
The president has to go to the border. I know all the arguments against it. It's a photo-op. It won't help. He will get no credit--let alone any cooperation--from the vandals in the Congress for having done so. He ...

1 day, 20 hours ago
Views: 313 • Comments: 8
Tweets: 0 • Rating: 0
Pie-onist Overlord
Tiny Hamster Predicts World Cup Semifinalists
2 days, 20 hours ago
Views: 318 • Comments: 0
Tweets: 5 • Rating: 0
Mich-again
Website to search Ammonium Nitrate storage Facilities in Texas
There has been chatter in Texas recently about how residents are supposed to know if there is an Ammonium Nitrate storage facility in their town. Well it turns out the State of Texas does have a website where residents can ...

3 days, 20 hours ago
Views: 605 • Comments: 12
Tweets: 16 • Rating: 3
William Barnett-Lewis
Recent Photographs
Inspired by Feline Fearless Leaeder's posting of some very nice floral photos, I decided first to post these in line in the thread and now to make a thread of them. Here's some of my recent bits. I hope you ...

1 week ago
Views: 368 • Comments: 2
Tweets: 0 • Rating: 7
CriticalDragon1177
Rooster Teeth - Red VS Blue - 4th of July PSA
A PSA for the chronically inept on America's Birthday! I have to thank my Friend, "golden izanagi" for alerting me to this. Happy Fourth of July!

1 week ago
Views: 427 • Comments: 0
Tweets: 1 • Rating: 0
Romantic Heretic
Gun Safety Gone Wrong
Considering how often we kick this subject around I thought this little video would be enjoyed by all.

1 week, 1 day ago
Views: 621 • Comments: 3
Tweets: 0 • Rating: 6
EiMitch
Escapist: Flat Earth Birth Control
This is a (sometimes NSFW) webcomic on the Escapist Magazine site called Critical Miss. The focus is usually on games, but they dib-&-dab in social issues sometimes. Like today: Flat Earth Birth Control From the first panel: So, the supreme ...

1 week, 1 day ago
Views: 517 • Comments: 0
Tweets: 0 • Rating: 2
 Frank says:

Weedley-Weedley-Wee -- Specifically, the small fret guitar-playing technique that musicians have a tendency to display while in pursuit of a cross between a waitress and a hoover vacuum... This, of course, from his book.