Home >
Google Closure: A New Way of Developing in JavaScript
Preface
Every day million people make use of Google products and these products are written mainly using one well known language: JavaScript!
What makes this online software stable, fast and responsive is a good use of the language and an excellent system of data compression and asynchronous loading. Today this power is available to everyone, since Google has released its magic tool under Apache 2 license. In the box we will find:
- a bullet-proof, OOP structured and complete js library called Closure
- an utility to merge js files into a single one (solving dependencies)
- a compiler to compress and optimize JavaScript code
- a FireBug extension for a better debug
- a template engine for both JavaScript and Java
Library overview
This is an huge (more than 400 JavaScript files!) JavaScript library organized into well documented "packages", "classes" and "subclasses" (quotes are mandatory because in JavaScript these entities don't exist but we can only think and realize a Java-like architecture). It makes intense use of a Java-doc syntax (http://java.sun.com/j2se/javadoc/) to describe each component, so it's possible learning functionalities and behaviors of the classes by reading these comments and generate an HTML document from the js files by using tools such jsdoc-toolkit (http://code.google.com/p/jsdoc-toolkit/) or the integrated Aptana's tool (http://docs.aptana.com/docs/index.php/Generating_HTML_documentation_from_ScriptDoc).
What makes Closure different from other libraries available nowadays is its goal, its structure and its approach to client side developing with JavaScript. Let me explain, jQuery, YUI, Dojo and others work really well and make possible great things with no effort and fast (both in terms of coding time required and code execution speed), so the "promise" of Closure is not to offer better algorithms (fine tuned loops to improve speed, faster DOM selector and so on) but rather a really better, organized and maintainable way of deploying JavaScript applications. And this is the point! Coding in Closure means thinking with object oriented principles in mind, create several js files, each representing a single class (customer.js, mediaplayer.js, loader.js and similar), organize the application architecture into packages and finally deploying it using the tools provided, obtaining a single, compressed, and safe JavaScript file which run extremely faster and doesn't contain dead code (unused functions and objects).
Thus, Closure is not simply a new js library, but a new way of programming in JavaScript! Google's team has engineered a framework which makes possible to write JavaScript at the same level as writing Java (in terms of the approach), by making Java developers more comfortable with an otherwise "foreign" and "poor" client side language and at the same time by offering new exciting tools and possibilities to frontend developers and promote good object oriented design. This design is realizable through an intense use of the JavaScript prototype mechanism, which is the natural way to realize "classes" in this language. Closure also provides tools to "simulate" packages definitions and imports (goog.provide() and goog.require()) and to easily subclassing custom class (goog.inherits(subClass, superClass)). Access modifiers (http://en.wikibooks.org/wiki/Java_Programming/Access_Modifiers) are defined through jsdoc syntax and checked at compile time (using the java tool provided), so a variable marked with /** @private */, will rise an error during the compilation if accessed from the outside. It's also possible to create and implement interfaces! You can create an interface in this way:
/**
* Shape interface
* @interface
*/
function IShape() {};
IShape.prototype.draw = function() {};
Then implement it:
/**
* @constructor
* @implements {IShape}
*/
function Square() {};
Square.prototype.draw = function() {
// draw a square
};
If, after implementing an interface, you will not provide all the methods declared in that interface's body, the compiler will throws an error.
The library includes then a series of objects coming from the Java world, such collections (Map, Set, Queue and so on) which will help you to work with data structures, buffers, logging and test/debugging tools (which can be used with every browser), classes to work with Gears (http://gears.google.com/) and to draw vector graphic in the browser (SVG and VML).
As their competitors, the library offers of course a set of normalizations in order to work easily across browsers:
- an excellent event framework (which also enable us to dispatch custom events)
- dom utilities (select, create and remove nodes, monitoring font size changes, monitor viewport changes and so on)
- the most complete ajax toolkit I ever seen (which enable us to handle queues of xhr calls and even make cross domain requests)
- several user interface components (tabs, editors, combo boxes, datepickers, sliders, menus and so on)
- drag and drop management
- animation effects
- date utilities (create, add, subtract dates and times, get numbers of days in a month and so on)
- a timer class to work with repeated/delayed task (it works very similar to the Actionscript 3 Timer)
...and more!
Deploying Closure web applications
Once we have written and tested our new powerful JavaScript classes and organized them into functional packages, it's time to deploy our application, in order to have only a single, optimized and high performance js file!
To reach this goal, we have to use 2 different tools: the first is the python script called "calcdeps.py" located in the folder "bin" under "closure" (you have first to do a checkout from the svn repository in order to get this folders), which will automatically recognize all the js files needed (by analyzing the several goog.require() inside files) and will generate a single js file including all the code required and the second is the compiler, which will compress and optimize the content of that file.
The compiler is the Closure's ace in the hole and, as Google says, converts JavaScript into better JavaScript (much better!) and it's available in three flavors: an online gui application, a Java command line tool (the best choice in my opinion) and a web API service.
The first is the easier way to compile our js files and consist in an application divided into two main areas, in the first we can add script urls and/or paste/write js code that will be then elaborated and rendered into the second area.
Is possible to choose among three different compressions: "whitespace only", as the name says, would removes only white spaces and lines feeds from the source but it also removes comments (every type of comment), "simple" which will also rename arguments names into a single letter in order to limit file size and "advanced", that will also remove unused functions, objects and arguments and will analyze the code in order to cleverly decide how it could be rewritten in a better way. Let's suppose to have a function like:
function hello(name) {
alert('Hello, ' + name);
}
and this function is called only once inside the code:
hello('New user');
...then the compiler will convert the original source to:
alert("Hello, New user");
The command line tool instead, consists in a Java utility (a jar file), which can be used from the terminal and allows us to write the converted code to a desired file under a desired directory. To use this tool, we have to download the archive from this url: http://closure-compiler.googlecode.com/files/compiler-latest.zip, unzip it, open the terminal, change the directory to "compiler-latest" (the folder we will get after unzipping the archive) and then run the following into the terminal: "java -jar compiler.jar [parameters]", where [parameters] are a series of commands allowed by the tool. To display the full commands/options list, we can just type "java -jar compiler.jar --help".
However the best solution is to invoke the compiler directly when running the python script, thus we will aggregate and compress our files at the same time (Follow the links at the bottom of this post to learn how to use this tools).
Conclusion
Google Closure is a mature and complex JavaScript framework with the goal of allow developers to realize the best stable and high performances client-side applications. It's not a "tool for everyone", it requires a good JavaScript experience, at least a minimun of OOP knowledge and basic knowledge of SVN (because it's the only way to download and obtain the sources), moreover you well need more time in order to realize a project, but for skilled developers and big projects it is definitely the framework to adopt... it takes JavaScript to a new level!
Useful links
Library home: http://code.google.com/p/closure-library/
API reference: http://closure-library.googlecode.com/svn/trunk/closure/goog/docs/index.html
Compiler download (Java): http://closure-compiler.googlecode.com/files/compiler-latest.zip
Web based compiler: http://closure-compiler.appspot.com/home
Dependencies script guide: http://code.google.com/closure/library/docs/calcdeps.html
Closure Templates home: http://code.google.com/p/closure-templates/
JsDoc Toolkit: http://code.google.com/p/jsdoc-toolkit/
Closure JsDoc tags: http://code.google.com/closure/compiler/docs/js-for-compiler.html#tags
...and finally, the dedicated section of my blog:




Facebook Application Development
Closure looks sweet. Until recently I insited on using Dojo for the better OOP architecture support as opposed to jQuery. Then I realised that the two serve different purposes. Now I use jQuery for augmenting my php applications. Would you say that Closure is better than Dojo? From the OOP tools revealed I would say that the Google guys drew a lot of inspiration from Dojo. Starting with the require/provide directives. But I didn't get a chance to dive in yet and I'm still searching for some demos, especially of the UI components in Closure.
And as a last note it definitely looks like another Google open source initiative. Perfect but perfectly unsupported :p
thank you very much for sharing helpful news; I hope this Google's project will help us in developing web faster
@cosmin: Google Closure is not better than Dojo, is different and has a more ambitious goal. As far I know, by using Dojo you won't get a single compiled, type checked, tested and safe file... the power of Closure are the tools provided with it! (the compiler and the dependencies calculator).
for those interested in Closure examples, check my blog, I will update it with new samples soon ;^)
There's another take on Closure that potential users should be aware of...
http://www.sitepoint.com/blogs/2009/11/12/google-closure-how-not-to-write-javascript/#
@Anonymous: as I said, the power of Google Closure, is not represented by its algorithms and how each line of code is written, but by the tools provided, that allow us to write JavaScript applications like never before!
Closure is the ideal tool to realize big and complex RIA based on ajax, ensuring a consistent, controlled and maintainable code. If you need a library which is fast, lightweight and simple to use, then keep using jQuery and similar. But if you want to do more than display a series of widgets in a page and/or manipulate some DOM node and realize animations, Closure is really better. Because it was designed with such goal in mind and we can see its quality and efficiency every day, by using gmail, google maps and so on.
I like it - but why didn't they write the compiler in JavaScript???
If the compiler optimizes function calls, maybe they could also allow, in JSDoc-Toolkit-style comment form, marking of functions as C-style inline functions which can be replaced by instances of the function everywhere (esp. for smaller functions)...
@Brett: could you write an example? I don't understand what do you mean :P
/**
* @inline
*/
function is_string (s) {
return typeof s === 'string';
}
...would then cause:
if (is_string(abc)) {
}
else if (is_string(def)) {
}
...to become:
if (typeof abc === 'string') {
}
else if (typeof def === 'string') {
}
I think this kind of thing would allow for more semantic/easier to read code which doesn't incur the penalty of invoking functions unnecessarily.
Don't use it. It is outdated (and abandoned) junk.
Don't use it. It is outdated (and abandoned) junk.
You have written a very good article describing the merits of Google Closure. Your English is much better by far than my Italian, but still your English is somewhat painful to read. If O'Reilly does not provide you with a copy editor, I volunteer for the job, free of charge. All you have to do is send me your article before publication.
@Kelly
I know, my english sucks, but currently I can't do better :(
Thanks for the support, I will send you my next article for a revision ;^)
This is a very informative and useful post for all.Internet marketing, also referred to as i-marketing, web-marketing, online-marketing, or e-Marketing, is the marketing of products or services over the Internet.The Internet has brought media to a global audience. The interactive nature of Internet marketing in terms of providing instant response and eliciting responses, is a unique quality of the medium. Internet marketing is sometimes considered to have a broader scope because it not only refers to the Internet, e-mail, and wireless media, but it includes management of digital customer data and electronic customer relationship management (ECRM) systems.Web design preston
Googles new open source JavaScript tools. I was really excited because Goggle typically deliver high quality stuff and getting access to the tools Google have used for their own state of the art on-line applications like Google Apps, Gmail etc. almost is too good to be true. I have downloaded it and taken the first look into the package. My first impression is very good and I have to admit that I’m impressed with it’s huge size and the way it is all structured. The features available really seams useful and I recommend that any web developer take a look at this new set of tools ASAP! Lets now take a look at Closure and I’ll briefly explain what I have uncovered.Speed dating London
"an huge" should be "a huge"
This is the only rule that follows phonetics, not spelling, so the rule to follow is how it sounds when spoken.
http://owl.english.purdue.edu/exercises/2/1/7
http://owl.english.purdue.edu/exercises/2/1/7/answers