Friday, April 19, 2024

Google Closure Tools Tutorial for Beginners

Google has a trio of open source technologies for developers who write large-scale JavaScript applications. Included in the first release were the Closure Compiler, a sophisticated JavaScript compiler, the Closure Library, a huge JavaScript code library designed for use with that compiler, and Closure Templates, a template system implemented in JavaScript and Java.

This is the technology that has powered the features of Gmail and several other high-profile Google applications (Google Docs, Reader, Calendar, Maps, among others). Google has designated this as their default library for JavaScript-based applications. Closure Tools, in turn, is a library designed for purposes other than those of other popular libraries, such as jQuery and Prototype.js.

It is commonly associated with dynamic solutions such as the Closure Compiler, which allows an efficient footprint for applications of any size and scalability. However, the learning curve is quite steep, there are a lot less examples and you need to find a way to integrate the compiler into your workflow. With a library like jQuery, just add a script reference (if you’re using a CDN, for example, you do not even need to physically download the file) and start coding.

So, in addition to the great Google web applications, the Closure is for what? It is an excellent option to consider for any medium or large application, regardless of the niche of technologies used in the back end. These applications almost always involve multiple developers and are likely to contain at least 100 kb of source code when referring to third-party libraries. If there is no built-in build system to match the scripts, an average page of an application of this size probably references 5 to 10 external scripts, if not more.

Closure Compiler

The Closure Compiler is arguably the main component of Closure Tools. It supports two primary optimization modes: “minification” (where the entire contents of the file are put on a single line) and “advanced compilation“.

JavaScript minifiers are not something new in the development community. A JavaScript compiler is not necessarily something new either, just as the compilers of other languages have also tackled this issue of compiling their codes natively. What’s unique about Closure Compiler is that it is a JavaScript-to-JavaScript compiler capable of performing code optimizations that were previously unknown and impossible to do with conventional tools. The Closure Compiler can be used as a standalone component in an existing JavaScript code base, or in conjunction with the Closure Library, which is designed for maximum optimization when used with the compiler.

Closure Library

The Closure Library is a huge library of JavaScript code optimized for use with the Closure Compiler. In theory, pairing with Compiler is optional. And, in fact, this is an extremely important feature in development environments, since it makes the build stage optional and dramatically speeds up some stages of the development. In the production environment, however, the use of the compiler is not optional, because the library’s uncompiled code is too large, and the strategy used to include the files is not designed to be efficient.

Closure Library code is updated periodically in a public subversion repository, which is fed from Google’s internal source control system. That does not mean that the quality is “pre-release” (or “beta”), it simply means that Google is confident enough to release more stable versions. Many parts of the Closure Library are actively in production at Google, and it comes with a huge set of unit tests. In the end, it is up to you or your organization to determine if it is stable enough for your needs.

Hello World Closure!

Let’s start by installing the environment to handle development using the Closure Library. To do this, install Git and run the following command:

git clone https://github.com/google/closure-library 

This will be enough to import all project files, dependencies, JavaScript, etc. If you are using Node.js, you can perform the import via command:

npm install google-closure-library

In the same directory, create a new JavaScript file named hello.js and add the following code to it. Note that, at first, we need at least the module of the Google Closure DOM passing to it, via JavaScript, a new h1 element and its style:

goog.require('goog.dom');
 
function hello() {
   var header = goog.dom.createDom('h1', {'style': 'background-color:#fff'}, 'Hello Closure!');
   goog.dom.appendChild(document.body, header);
}

The following code listing shows the HTML content (save it to the hello.html file) to import the Closure JavaScript files and the call to the hello() function of the hello.js file:

<html>
  <head>
	<meta charset="utf-8" />
    <script src="closure-library/closure/goog/base.js"></script>
    <script src="hello.js"></script>
  </head>
  <body onload="hello()">
  </body>
</html> 

The result of this execution can be visualized in Figure 1.


Figure 1. Hello World Closure example

Let’s say now that we want the ability to change the contents of a div tag anywhere in our HTML. Let’s start with a bit of HTML like the following structure:

<html>
<head>
    <meta charset="utf-8" />
    <title>Closure Div Test</title>
</head>
<body>
    <div id="myDiv"></div>

    <script src="closure-library/closure/goog/base.js"></script>
    <script src="dynamicDiv.js"></script>
    <script>dynamicDiv.insert('myDiv');</script>
</body>
</html> 

Notice that at this point we are replicating the same information about importing Closure. However, this time we have an empty div in the body of the page whose id will be used as identifier in Closure via insert() function placed in the <script> tag of the page. Before finalizing the understanding, create a new file dynamicDiv.js and insert the following code on it:

goog.provide('dynamicDiv');
goog.require('goog.dom');

dynamicDiv.insert = function(elementId) {
    var container = goog.dom.getElement(elementId);
    container.innerHTML = "<h2>Hello Closure, my div must be placed here!</h2>";
}

Now, as we’ve talked about before, the goog object scattered throughout the code comes from the Closure Library. The provide() function of Closure is used to import Closure objects declared inside HTML pages that need to be handled in that particular file in our script. In this case, we create a new Closure object named “dynamicDiv” and make its insert() function publicly available in the files that import dynamicDiv.js. The function basically receives the element id and inserts new content into it. Figure 2 shows what you should see when opening the HTML file in your browser.


Figure 2. Result of the execution of the previous example.

In short, the function uses one of the DOM’s helper utilities from the goog.dom.getElement library to find the element in which you want to put the text, and for now simply sets your inner HTML to a hello message:

var container = goog.dom.getElement(elementId);
container.innerHTML = "<h2>Hello Closure, my div must be placed here!</h2>"; 

The most interesting part of the code are these first two lines:

goog.provide('dynamicDiv');
goog.require('goog.dom'); 

They are parts of the library’s dependency management and namespace system. So let’s now understand how such management works within Google Closure.

Conclusion

These were just a few basic examples of the power of this API in relation to the use of requests, be they synchronous or asynchronous. Most JavaScript APIs provide capabilities to enable communication of your applications with HTTP services via Ajax, and Google Closure is not far behind. Do some other tests, search the web for some other free services, such as the Post Office Web Service, for example, and try to communicate by sending the required parameters and processing the returned responses. This is a great way to practice the concepts learned in the language at the expense of real scenarios to better display the knowledge.

About the Author

Diogo Souza works as a Java Developer at PagSeguro and has worked for companies such as Indra Company, Atlantic Institute and Ebix LA. He is also an Android trainer, speaker at events on Java and mobile world.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured