Compressing your JavaScript with Closure Compiler


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.

How can I use the Closure Compiler?

You can use the Closure Compiler as:

An open source Java application that you can run from the command line.

A simple web application.

A RESTful API.

To get started with the compiler, see "How do I start" to the right.

What are the benefits of using Closure Compiler?

  • Efficiency. The Closure Compiler reduces the size of your JavaScript files and makes them more efficient, helping your application to load faster and reducing your bandwidth needs.
  • Code checking. The Closure Compiler provides warnings for illegal JavaScript and warnings for potentially dangerous operations, helping you to produce JavaScript that is less buggy and and easier to maintain.

Example: What Can Closure Compiler Do For You?

The Hello World of the Closure Compiler Service UI

The easiest way to get familiar with the Closure Compiler service is by optimizing a few simple functions in the service's web UI.
  1. Access the Closure Compiler UI by opening this page in another tab or window: http://closure-compiler.appspot.com.
  2. You should see the Closure Compiler UI prepopulated with a simple Hello World function:

  3. Click "Compile" to see the result:


That's it! You now have a much smaller version of the JavaScript code that functions identically to the original. The Closure Compiler service reduced the code from 92 bytes to just 55 bytes by removing comments and whitespace and renaming basic symbols.
For your convenience, the Closure Compiler service hosts the output file default.js on its servers for one hour. You can access the URL of the output file by copying the location of the link that's provided above the output pane, where it says The code may also be accessed at {filename}. If you make any changes to the original JavaScript code and re-optimize it during that hour, Closure Compiler service overwrites the output file with the new results as long as you leave the @output_file_name parameter unchanged at the top of the input field. You can use this feature as a quick way to test your compiled code by linking directly to the file from your test application. Do do not link to it from production servers.
Note: To prevent abuse, the Closure Compiler limits the number of consecutive compiles that you can run. If you see the message Too many compiles performed recently. Try again later, it means you've temporarily exceeded the limit.

Optimize a JavaScript file

You can also optimize the contents of one or more JavaScript files using the Closure Compiler UI.
  1. Copy and paste the URL http://code.google.com/closure/compiler/samples/tutorial2.js into the Add a URL box. This file contains unoptimized code for creating nodes in a DOM tree.
  2. Click Add. (If you had more than one file to add, repeat Steps 1 and 2 until you've added all of them. You can also type the file name(s) directly into the text area if you prefer.)
  3. If you want the Closure Compiler service to serve the compressed file, choose a name for the output file using the @output_file_name parameter at the top of the input field. Note that the default for the output file name is default.js but you should change it to a more meaningful name for your project. Also note that the Closure Compiler service hosts the output file on its servers for an hour.
  4. Click Compile.

You should see the optimized JavaScript in the right hand panel, like this:
To use the optimized code, you can cut and paste it into your source file, download the file into your directory, or link to the file directly in your script tag (for up to one hour).
You have just worked through examples of optimizing simple functions in the Closure Compiler service UI. If you'd like to build the Closure Compiler service's JavaScript optimization process into a larger system, then you should talk directly to the Closure Compiler service API. Learn more at Getting Started with the Closure Compiler Service API.

--
Thanks
Suresh Devaraj

Using HTML 5 for performance improvements

Using HTML 5 for performance improvements

Author: Jens Meiert, Google Webmaster

Recommended experience: Basic/Advanced HTML

In HTML, you can already reduce content size significantly by omitting optional tags. HTML 5, which is still under development, offers you a couple more options to decrease your file size beside leaving out optional stuff. Here we'll feature some basic measures to reduce content size a bit more, plus the async and defer attributes useful to improve script execution.

DTD

HTML 5 allows you to set the document type by just stating (in any form, as the DTD is case-insensitive)

<!DOCTYPE html>

Compare that to

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

and you'll notice that the HTML 5 DTD is much shorter.

Encoding

When you specify the encoding of your document, HTML 5 is a bit easier to use and also more lightweight:

<meta charset="utf-8">

will do what

<meta http-equiv="content-type" content="text/html; charset=utf-8">

does otherwise; your browser usually knows that it's dealing with HTML.

type attributes

Another thing that works in HTML 5 – today – is that you can leave out all the type attributes related to MIME types. These are the attributes such as type="text/css" or type="text/javascript", which describe the type of contents the element in question contains or links to.

Instead of <style type="text/css"> you can just write <style>; instead of writing <script type="text/javascript">, you can just use <script>. You can omit type="text/css" in almost all document types actually, even in XHTML, but HTML 5 makes all this even simpler since consistent.

async (and defer)

async and defer are attributes to be used in conjunction with the script element.

To explain why these attributes are useful to improve performance, it's best to see what happens when they're not used – respective script would be fetched and executed immediately, before the user agent (browser) continues parsing the page. Sometimes this behavior is desirable, sometimes it's not.

The new async attribute allows that respective script will be executed asynchronously, as soon as it is available. HTML 4, which already includes the defer attribute, states that defer "provides a hint to the user agent that the script is not going to generate any document content (e.g., no document.write in JavaScript) and thus, the user agent can continue parsing and rendering".

If the async attribute is not used but the defer attribute is present, the script is executed when the page has finished parsing. The defer attribute may be specified even if the async attribute is specified. This allows legacy browsers that only know defer to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.


--
Thanks
Suresh Devaraj