Make the Web Faster

Compressing your JavaScript with Closure Compiler

Author: Robert Bowdidge, Software Engineer

Recommended experience: Some experience creating web pages.

Overview

The best way to make your web page more responsive is to minimize the number of files and size of files that must be downloaded when the page is loaded. Reducing the number of files loaded avoids hitting maximum simultaneous download limits in browsers. Reducing file size cuts the time needed to send all the bytes over the Internet. Some tools already exist to minimize files and file sizes. Spriting tools and image compression tools let you minimize the number and size of images; gzip and HTML compression tools let you reduce the size of your HTML files.

JavaScript minimization tools give you another way to reduce your overall download size. These tools work on JavaScript source code for your webpage. The tools remove unneeded spaces and comments, and sometimes even change the names of variables in your program to shrink the file size even more. However, the commonly used minimization tools miss additional ways to compress the code even further.

The Closure Compiler, a new minimization tool, finds ways to compress your JavaScript code even further than existing minimization tools. It achieves additional compression by using compiler-like technology to rewrite your JavaScript into a much smaller form, while ensuring the code still runs correctly. Closure Compiler can condense several files into one single file, and can easily reduce the size of your JavaScript in half. The Closure Compiler also does syntactic checks and static analysis for your program, so it flags potential syntax and type errors and highlights code patterns that may not work well on all browsers.

Example: What Can Closure Compiler Do For You?

As a starting example, imagine you're a web developer for a large newspaper, the Esmeralda Times, and you want to try optimizing the code for your home page. Go to the Closure Compiler web service UI at http://closure-compiler.appspot.com. Notice that the web application starts off with a simple Hello World example; if you click "Compile", Closure Compiler minimizes the code and shows it on the right hand side.

But you don't care about "Hello World"; you care about speeding up your web page.

Our fictional example here (borrowed from an actual media website) loads six separate JavaScript files when loading the home page, for a total of about 227,000 bytes of code. Two of the files represent the Esmeralda Times's own code, and the rest uses the Prototype and script.aculo.us JavaScript libraries.

Click the "Reset" link to delete the "Hello World" portion of the code in the Closure Compiler web service UI. Add the URLs for the JavaScript files in your home page, either by typing a URL into the text field and pressing "Add", or by typing these explicit requests to load specific pages into the input section of the Closure Compiler web service:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @code_url http://www.esmeraldatimes.com/sitewide/sitewide.js
// @code_url http://www.esmeraldatimes.com/sitewide/main.js
// @code_url http://www.esmeraldatimes.com/js/ext/prototype/prototype.js
// @code_url http://www.esmeraldatimes.com/js/ext/scriptaculous/scriptaculous.js?load=effects,dragdrop
// @code_url http://www.esmeraldatimes.com/js/ext/scriptaculous/effects.js
// @code_url http://www.esmeraldatimes.com/js/ext/scriptaculous/dragdrop.js
// ==/ClosureCompiler==

Now, choose a compile mode. You have these choices:

  • Whitespace Only mode simply removes unnecessary whitespace and comments. Selecting "Whitespace Only" mode and pressing compile presents you with a single file of JavaScript with 164K of source code, 28% smaller than the original 227K of source code.

  • Simple mode is a bit more sophisticated. It optimizes JavaScript function bodies in several ways, including renaming local variables, removing unneeded variables and code, and replacing constant expressions with their final value (such as converting "1+3" to "4"). It, however, won't remove any functions or variables that might be referenced outside your JavaScript. It shrinks the code by 42% from 227K to 132K

  • Advanced mode does even more sophisticated changes to your code. Try selecting "Advanced" optimizations, compile the code, and look at the results. This code looks much less like your original code; it renames all functions to short names, deletes functions it does not believe are used, replaces some function calls with the function body, and does several other optimizations that shrinks the code even further. Typically, you can't use Advanced Mode on existing JavaScript code without providing some additional information about functions in the code that need to be visible elsewhere and code elsewhere that might be called from within your JavaScript. However, it's worth noting that the Advanced mode cut the code size from 227K to 86K - 62% smaller than the original code. If you'd like this file to load in 1/3 the time of the original, you might find it worthwhile to give Advanced mode all the information to do this change correctly.

Here is an example of what a simple optimization of the JavaScript files used by the Esmeralda Times might look like:

Screenshot of Closure Compiler web service

Note that you can download the resulting compressed source from a link in the UI, or copy and paste the optimized JavaScript directly from the Closure Compiler web service UI into your source file.

Best of all, you can still debug this compressed code by generating a Closure Inspector source map. The Firebug debugger uses this source map to point you to the lines of original source code that correspond to the optimized code that you're debugging. Generating the Closure Inspector source maps requires running the Closure Compiler on your local machine using the source or pre-built jar files.

Now you've seen what the Closure Compiler can do for the Esmeralda Times; go look at the JavaScript brought in by your own web application, and see what it can do for your actual code!

What Else Can Closure Compiler Do For You?

The Closure Compiler can also warn you about incorrect code. Because it is parsing your JavaScript code, it can warn you about compile errors without requiring you to load the code into your browser. You can be sure you have no syntax errors that will mysteriously appear when you click on an infrequently-used button. The Closure Compiler also can identify common code patterns that are not consistently handled in all browsers, such as trailing commas in arrays (a = [1, 2, 3, ];) Some browsers create three elements in the array, others four; such inconsistencies can create some hard-to-track down bugs. Closure Compiler can also identify invalid math operations, code that can never be executed, or function calls where you're not passing enough arguments.

In Advanced Mode, Closure Compiler can also use type annotations in your code to find logic errors in your program - cases where you intend to pass a Money object, but accidentally pass an AccountNumber object, for example. This gives you the bug-finding advantages of typed languages like Java, but still keeps the fast, fun coding experience of JavaScript.

How Does Closure Compiler Work?

Closure Compiler is actually a JavaScript compiler, but rather than generating machine code like most compilers, it produces valid JavaScript code. It can rewrite JavaScript code in many interesting ways. It can identify constant expressions and replace them with constant values, replacing (15 * 280) + 16 with 4216. By doing this, it cuts 15 characters to 5. More importantly, it gives you the freedom to write your code in a clear and understandable way, and frees you from worrying about the final size of the code. Functions called in only one or two places can be inlined, replacing the function call with the contents of the function body, saving the space needed for the function declaration. Closure Compiler can even tell when two different variables are never used at the same time, letting both share the same name and ensuring that as many variables as possible use very short names for better gzip compression.

Closure Compiler is open-source; examine or download the source at http://code.google.com/closure/compiler/ to build it yourself and write your own JavaScript code optimizations!

Conclusion

Closure Compiler gives JavaScript developers a new and better way to compress JavaScript code, and helps your web pages using JavaScript load faster than ever. Try it out on your JavaScript sources, and see what a difference it can make.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.