O'Reilly logo

Closure: The Definitive Guide by Michael Bolin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Preface

JavaScript borrows many great ideas from other programming languages, but its most unique, and perhaps most powerful, feature is that any code written in JavaScript can run as-is in any modern web browser. This is a big deal, and it is unlikely to change anytime soon.

As web browsers improve and become available on more devices, more applications are being ported from desktop applications to web applications. With the introduction of HTML5, many of these applications will be able to work offline for the first time. In order to create a superior user experience, much of the logic that was previously done on the server will also have to be available on the client. Developers who have written their server logic in Java, Python, or Ruby will have to figure out how to port that server logic to JavaScript. Tools like Google Web Toolkit, which translate Java to JavaScript can help with this, though such tools are often clumsy because the idioms from one programming language do not always translate smoothly into that of another. However, if your server code is written in JavaScript, this is not an issue.

I believe that the use of server-side JavaScript (SSJS) is just beginning. Previously, most implementations of JavaScript were too slow to be considered a viable option for server code. Fortunately, the recent competition among browser vendors to have the fastest JavaScript engine makes that difference far less significant (http://shootout.alioth.debian.org).

Because of the emerging support for offline web applications, it is compelling to write both the client and the server in the same programming language to avoid the perils associated with maintaining parallel implementations of the same logic. Because it is extremely unlikely that all of the major browser vendors will adopt widespread support for a new programming language, that will continue to force the client side of a web application to be written in JavaScript, which in turn will pressure developers to write their servers in JavaScript as well. This means that the size of the average JavaScript codebase is likely to increase dramatically in the coming years, so JavaScript developers will need better tools in order to manage this increased complexity. I see Closure as the solution to this problem.

Closure is a set of tools for building rich web applications with JavaScript, and brings with it a new approach to writing JavaScript and maintaining large JavaScript applications. Each tool in the suite is designed to be used independently (so jQuery developers can make use of the Closure Compiler and Closure Templates, even if they are not interested in the Closure Library), but they are most effective when used together.

Many JavaScript toolkits today focus on DOM utilities and UI widgets. Such functionality is incredibly useful when building the interface for a web application, but the emergence of SSJS will require an equivalent effort in building server-side JavaScript libraries. There, the focus is likely to be on data structures and efficient memory usage, both of which are already woven into the Closure framework.

I believe that Closure will play an important part in making web applications faster and more reliable. As an active user of the Web, I have a vested interest in making sure this happens. That’s why I had to write this book. Rather than document every API in Closure, I have tried to provide detailed explanations for the most commonly used APIs, particularly those that are unique to the Closure approach.

Indeed, learning Closure will change the way you develop JavaScript applications.

My Experiences with Closure

When I worked at Google from 2005 to 2009, I used Closure to help build Google Calendar and Google Tasks. When the initial work on Calendar was done in 2005, only the Compiler was available, and it was (and is) known internally as the JavaScript Compiler. At the time, there were a number of common JavaScript utilities that teams would copy from one another. This led to many forked versions, so improvements to one copy did not propagate to the others.

Meanwhile, the JavaScript codebase for Gmail had grown so large and complex that developers complained that it was too hard for them to add new features. This triggered a rewrite of the Gmail client, which precipitated the development of the two other major tools in the Closure suite: the Library and Templates. The Library was simply named “Closure,” as it was a play on the programming construct used so frequently in JavaScript, as well as the idea that it would bring “closure” to the nightmare that was JavaScript development at Google.

Like many other JavaScript toolkits, the goal of Closure was to provide a comprehensive cross-browser library. Instead of adopting an existing solution, such as Dojo, Google decided to roll its own. By having complete control of its library, it could ensure that the API would be stable and that the code would work with its (then) secret weapon: the Closure Compiler. This made it possible to buck the trend established by libraries like Prototype that encouraged the use of absurdly short function names. In Closure, nondescript function names such as $ were eschewed in favor of more descriptive ones because the Compiler would be responsible for replacing longer names with shorter ones.

The build system at Google was amended to express dependencies between JavaScript files (these relationships are reflected by goog.provide() and goog.require() statements in the Closure Library). For the first time, dependencies were organized into well-named packages, which introduced a consistent naming scheme and made utilities easier to find. In turn, this made code reuse more straightforward, and the Library quickly achieved greater consistency and stability than the previous dumping ground of JavaScript utilities. This new collection of common code was far more trustworthy, so teams started to link to it directly rather than fork their own versions, as they were no longer afraid that it would change dramatically out from under them.

Finally, Closure Templates (known internally as Soy) were created to address the problem that most existing templating systems were designed to generate server code, but not JavaScript code. The first version of Soy generated only JavaScript, but it was later extended to generate Java as well, to provide better support for the “HTML Decorator” pattern described in Chapter 8, User Interface Components.

By the time I started work on Google Tasks, these tools had matured considerably. They were invaluable in creating Tasks. While the Calendar team was busy replacing their original utility functions with Closure Library code and swapping out their home-brewed (or Bolin-brewed) template solution with Soy, I was able to make tons of progress on Tasks because I was starting with a clean slate. Because Gmail has been stung by hard-to-track-down performance regressions in the past, the barrier for getting code checked in to Gmail is high. In integrating Tasks with Gmail, I was forced to gain a deeper understanding of the Closure Tools so I could use them to optimize Tasks to the satisfaction of the Gmail engineers. Later, when I integrated Tasks in Calendar, I learned how to organize a sizable JavaScript codebase so it could be incorporated by even larger JavaScript projects.

One of my major takeaways from using Closure is that trying to address limitations of the JavaScript programming language with a JavaScript library is often a mistake. For example, JavaScript does not have support for multiline strings (like triple-quote in Python), which makes it difficult to create templates for HTML. A bad solution (which is the one I created for Google Calendar back in 2005 that they were still trying to phase out so they could replace it with Soy in 2009) is to create a JavaScript library like jQuery Templates (http://plugins.jquery.com/project/jquerytemplate). Such a library takes a string of JavaScript as the template and parses it at runtime with a regular expression to extract the template variables. The appeal, of course, is that implementing something like jQuery Templates is fairly easy, whereas implementing a template solution that is backed by an actual parser is fairly hard (Closure Templates does the latter). In my experience, it is much better to create a tool to do exactly what you want (like Closure Templates) than it is to create a construct within JavaScript that does almost what you want (like jQuery Templates). The former will almost certainly take longer, but it will pay for itself in the long run.

Audience

As this is a book about Closure, a suite of JavaScript tools, it assumes that you are already familiar with JavaScript. Nevertheless, because so many JavaScript programmers learn the language by copying and pasting code from existing websites, Appendix B is included to try to identify incorrect assumptions you may have made about JavaScript when coming from your favorite programming language. Even those who are quite comfortable with the language are likely to learn something.

Other than the Closure Tools themselves, this book does not assume that you are already familiar with other JavaScript tools (such as JSLint and YUI Compressor) or libraries (such as Dojo and jQuery), though sometimes parallels will be drawn for the benefit of those who are trying to transfer their knowledge of those technologies in learning Closure. The one exception is Firebug, which is a Firefox extension that helps with web development. In addition to being considered an indispensable tool for the majority of web developers, it must be installed in order to use the Closure Inspector. Unlike the other tools in the suite, the use of the Closure Inspector is tied to a single browser: Firefox. Because Firebug is updated frequently and has comprehensive documentation on its website, this book does not contain a tutorial on Firebug because it would likely be outdated and incomplete. http://getfirebug.com should have everything you need to get started with Firebug.

Finally, this book makes a number of references to Java when discussing Closure. Although it is not necessary to know Java in order to learn Closure, it is helpful to be familiar with it, as there are elements of Java that motivate the design of the Closure Library. Furthermore, both Closure Templates and the Closure Compiler are written in Java, so developers who want to modify those tools will need to know Java in order to do so. This book will not teach you Java, though a quick search on Amazon will reveal that there of hundreds of others that are willing to do so.

ECMAScript Versus JavaScript

This book includes several references to ECMAScript, as opposed to JavaScript, so it is important to be clear on the differences between the two. ECMAScript is a scripting language standardized by Ecma International, and JavaScript is an implementation of that standard. Originally, JavaScript was developed by Netscape, so Microsoft developed its own implementation of ECMAScript named JScript. This means that technically, “ECMAScript” should be used to refer to the scripting language that is universally available on all modern web browsers, though in practice, the term “JavaScript” is used instead. To quote Brendan Eich, the creator of JavaScript: “ECMAScript was always an unwanted trade name that sounds like a skin disease.” To be consistent with colloquial usage (and honestly, just because it sounds better), JavaScript is often used to refer to ECMAScript in this book.

However, ECMAScript is mentioned explicitly when referring to the standard. The third edition of the ECMAScript specification (which is also referred to as ES3) was published in December 1999. As it has been around for a long time, it is implemented by all modern web browsers. More recently, the fifth edition of the ECMAScript specification (which is also referred to as ES5) was published in December 2009. (During that 10-year period, there was an attempt at an ES4, but it was a political failure, so it was abandoned.) As ES5 is a relatively new standard, no browser implements it fully at the time of this writing. Because Closure Tools are designed to create web applications that will run on any modern browser, they are currently designed around ES3. However, the Closure developers are well aware of the upcoming changes in ES5, so many of the newer features of Closure are designed with ES5 in mind, with the expectation that most users will eventually be using browsers that implement ES5.

Using This Book

This book explains all of the Closure Tools in the order they are most likely to be used.

  • Chapter 1, Introduction to Closure, introduces the tools and provides a general overview of how they fit together with a complete code example that exercises all of the tools.

When working on a JavaScript project, you will spend the bulk of your time designing and implementing your application. Because of this, the majority of the book is focused on how to leverage the Closure Library and Closure Templates to implement the functionality you desire. Of all the topics covered in this part of the book, the rich text editor is the one that appears most frequently in the Closure Library discussion group. To that end, I recruited goog.editor expert Julie Parent as a contributing author, so fortunately for you and for me, Julie wrote Chapter 9.

The next three chapters will explain how to get the most out of your source code using the Closure Compiler:

  • Chapter 12, Using the Compiler, demonstrates how to minify code using the Compiler.

  • Chapter 13, Advanced Compilation, goes beyond the Compiler as a minifier and explains how to use it as a proper compiler, showing how to identify errors at compile time and achieve size reductions that go far beyond what ordinary minification can do.

  • Chapter 14, Inside the Compiler, explores the source code of the Closure Compiler itself and reveals how to use it as the basis of your own JavaScript tools.

The remaining chapters will focus on evaluating your code to ensure that it does what you designed it to do:

The first two appendixes provide additional information about JavaScript: they are designed to enrich your knowledge of the language. The third appendix discusses a build tool that unites the Closure Tools in a way that makes them easier to use.

  • Appendix A, discusses two approaches for simulating inheritance in JavaScript and focuses on the advantages of the approach used by Closure.

  • Appendix B, explains features of the language that often trip up developers, both old and new.

  • Appendix C, introduces a build tool of the same name that can dramatically simplify and speed up development with the Closure Tools.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, and email addresses.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as filenames, file extensions, variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This icon signifies a tip, suggestion, or general note.

Caution

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, copyright holder, and ISBN. For example: “Closure: The Definitive Guide by Michael Bolin (O’Reilly). Copyright 2010 Michael Bolin, 978-1-449-38187-5.”

If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at .

Safari® Books Online

Note

Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.

With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features.

O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707 829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

http://oreilly.com/catalog/9781449381875/

To comment or ask technical questions about this book, send email to:

For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our website at:

http://www.oreilly.com

Acknowledgments

I would like to start out by thanking my contributing author, Julie Parent, for her outstanding work on the rich text editing chapter, and perhaps more importantly, for her many years of work on the rich text editor widget itself while working at Google. What started out as a component for the (now forgotten) Google Page Creator product way back in 2005 has become a critical widget for many Google Apps today (most notably, Gmail). If they gave out doctorates for the field of “little-known browser bugs that make rich text editing in the browser nearly impossible,” then Julie would be a leader in the field and Chapter 9 could have been used as her dissertation. Julie, thank you so much for putting the same amount of diligence into writing your chapter as you did in developing the rich text editor in the first place.

Next, I owe a tremendous amount of thanks (and a nice bottle of scotch) to Nick Santos, who has been a phenomenal technical reviewer. He responded to the call for reviewers with alacrity and his enthusiasm in the project never waned. In doing a review of this book, Nick effectively engaged in a 35,000-line code review, and provided so many corrections and helpful suggestions that this book probably would not even be worth reading if Nick had not read it first. In addition to all of his work as a reviewer, Nick played (and continues to play) an active role in open-sourcing the Closure Compiler as well as its development. You can see the breadth and depth of Nick’s knowledge in the Closure Compiler discussion group, as he is an extremely active member there, as well.

In addition to Nick, I was fortunate enough to have two other Google engineers who helped build pieces of the Closure Tools suite to participate in the review process. Erik Arvidsson (who co-created the Closure Library with Dan Pupius—thanks, Dan!) provided lots of valuable feedback on the chapters on the Library. Likewise, the creator of Closure Templates, Kai Huang, provided detailed criticisms of the chapter on Soy. Many thanks to both Erik and Kai for lending their time and expertise to ensure that the story of their work was told correctly.

As Nick explained in the foreword, taking a closed source project and turning it into an open source one is a lot of work, so I would also like to recognize those who played an important role in that process. Nathan Naze, Daniel Nadasi, and Shawn Brenneman all pitched in to open source the Closure Library. Robby Walker and Ojan Vafai also helped out by moving the rich text editor code into the Library so that it could be open-sourced, as well. Extra thanks to Nathan for continuing to manage the open-sourcing effort and for giving talks to help get the word out about the Library. It is certainly an example of well-spent 20% time at Google.

In that same vein, I would also like to thank Dan Bentley for helping ensure that all of this Closure code made it out into the open. Google is lucky to have him working in their Open Source Programs Office, as his genuine belief and interest in open source benefits the entire open source community.

I would also like to thank my former teammates on the Closure Compiler team who all contributed to the open source effort as well as Compiler development: Robert Bowdidge, Alan Leung, John Lenz, Nada Amin, and Antonio Vincente. Also, thanks to our manager, Ram Ramani, who supported this effort the whole way through and helped coordinate the open source launch. I also want to give credit to our intern, Simon Mathieu, who worked with me to create the Closure Compiler Service.

Thank you to Joey Schorr for navigating the world of not just Firefox extensions, but also Firebug extensions, in order to create and maintain the Closure Inspector. Without Joey, all of our compiled JavaScript would be filled with alert() statements (though for some of us, that’s how our uncompiled JavaScript looks, too!).

Five hundred pages later, I now have a much better appreciation for the work of David Westbrook and Ruth Wang, who as tech writers at Google produced much of the public documentation for Closure Tools that is freely available on http://code.google.com. Thanks to both David and Ruth for their attention to detail in explaining what these Closure shenanigans are all about.

Although I have already dropped the names of a lot of Googlers, I know that there are many more who have contributed to Closure over the years, so I am sure that I am leaving some out, and I apologize for any omissions. I hope that all of you continue to make Closure the best choice when choosing a set of tools for building amazing web applications. As frontend engineers working on products at Google, your work already has the opportunity to reach many users around the world. But now that all of Closure is open source, you have the opportunity to have a similar impact on web developers. I hope that opportunity does not go to waste!

Believe it or not, there were also people who never worked at Google who also helped make this book possible. Thank you to my editors, Julie Steele and Simon St.Laurent, who helped green-light this project back in November 2009, less than a month after the Closure Tools were even open-sourced. I would also like to thank my “unofficial editors,” which includes everyone who posted a comment on the Rough Cut, especially Donald Craig and Derek Slager. Not only did all of you help make this book better, but you also gave me the confidence that someone was actually going to read this thing someday and that it was worth writing.

Finally, I would like to thank Sarah, without whose unrelenting patience and support I would not have been able to finish this book. In many ways, writing a book is a lonely endeavor, but you never let it get that way because you were there to encourage me throughout the entire process. I would also like to thank my mom, whose love of books undoubtedly helped inspire me to write this one. Thanks to my sister Katie for letting me know when she noticed a jump in my page count graph, as it means a lot to know that someone out there cares and is paying attention. And last but not least, I would like to thank my father for betting me $500 that I would not be a published author by 30, which provided the extra motivation I needed to see this book all the way through. I’ll take my winnings in cash, old man!

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required