Home arrow AJAX & Prototype arrow Page 2 - Google's Closure Compiler Service API: Optimizing a JavaScript File

Creating a simple JavaScript file for further optimization - AJAX

In this third part of the series, I develop an example that illustrates how to use the Closure Compiler Service API for optimizing a JavaScript file via the set of PHP classes defined previously. In this example, the level of optimization applied to the target file is basic, limited to stripping its white space and nothing else.

TABLE OF CONTENTS:
  1. Google's Closure Compiler Service API: Optimizing a JavaScript File
  2. Creating a simple JavaScript file for further optimization
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
October 04, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

To demonstrate how to use the Closure Compiler Service API with the set of PHP classes defined in this and previous parts of this series, it's mandatory to create a JavaScript file that can be optimized by the service, and then sent back to the browser.

To fit this requirement, below I created a somewhat rudimentary file called "function.js," whose trivial definition looks like this:

function createDiv(idAttr, classAttr) {
    // create the div
    var div = document.createElement('div');
    // assign the 'id' attribute to the div element
    div.setAttribute('id', idAttr);
    // assign the 'class' attribute to the div element
    div.setAttribute('class', classAttr);
    // append the div element to the document
    document.getElementsByTagName('body')[0].appendChild(div);
};
// call the previous function
createDiv('divid', 'divclass');

As you can see above, this sample JavaScript file defines a function named "createDiv()," which uses a few common DOM methods to first create a "div" element, then assign to it an "id" and a "class" HTML attribute, and finally append the pertinent element to the end of the web page. Lastly, the function is called with a couple of basic arguments that are self-explanatory.

Having shown the definition of the previous "function.js" file, it's time to put all of the pieces together and see how to apply a basic level of optimization to it with the Closure Compiler Service API. The full details of this process will be discussed below.

Seeing Google's Closure Compiler Service API in action: applying a basic level of optimization to the earlier JavaScript file

If you're like me, you want to see how the PHP classes built before can be used for optimizing the JavaScript file coded above via the Closure Compiler Service API. Well, it's time to set up a concrete example that shows how to accomplish this in a few simple steps.

At its most basic level, the API requires four POST parameters to do its business as expected. The first one is called "js_code" and must contain the JavaScript snippet that will be optimized (although its URL can be passed too). The second argument is named "compilation_level" and can be used for specifying the level of optimization the will be applied to the target JavaScript code.

The other two are called "output_format" and "output_info" respectively. They come in handy for controlling in which format the compiled output will be served to the client (text, XML or JSON), and for specifying what kind of data will be returned to the browser (compiled code, statistics, etc.).

The API also supports some additional arguments that perform more advanced optimizations, but those will be discussed in depth in upcoming tutorials. For the moment, focus your attention on the following example. It first compiles the previous "function.js" JavaScript file by removing its white space, and then returns the compiled code in text/javascript format:  

<?php

// example using optimization level = WHITESPACE_ONLY
try {
 
    // include the autoloader class
    require_once 'Autoloader.php';
    Autoloader::getInstance();

    // create an instance of the file handler class and read the specified JavaScript file
    $fileHandler = new FileHandler;
    $js = $fileHandler->read();
   
    // build the array of arguments that will be passed to the closure compiler API
    $data = array(
         'js_code' => $js,
         'compilation_level' => 'WHITESPACE_ONLY',
         'output_format' => 'text',
         'output_info' => 'compiled_code'
    );
   
    // create an instance of the ClosureCompilerHandler class
    $compilerHandler = new ClosureCompilerHandler($data);
    // query the closure compiler API and get the compiled JavaScript function
    $response = $compilerHandler->sendRequest();
    $compilerHandler->sendHeader('js');
    // print to screen the compiled JavaScript function
    echo $response;
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

Even though the above script seems to be rather complex, its driving logic is fairly simple to follow. In this case, the script simply grabs the Singleton instance of the autoloader to include all of the PHP classes that you saw before, and uses the file handler to fetch the contents corresponding to the previous "function.js" JavaScript file.

Finally, an array containing the fourth parameters required by the Closure Compiler Service API is passed to the "ClosureCompilerHandler" class, which queries the API and returns the compiled version of the target file. Since in this example, the value assigned to the "compilation_level" argument is WHITESPACE_ONLY, this is the output that the compiler sends back to the client:   

function createDiv(idAttr,classAttr){var div=document.createElement("div");div.setAttribute("id",idAttr);div.setAttribute("class",classAttr);document.getElementsByTagName("body")[0].appendChild(div)}createDiv("divid","divclass");

That worked like a charm! As you can see above, the compiler has effectively removed all the white space included in the target JavaScript file, thus stripping some bytes from its original size. While this is only a basic example, it shows in a nutshell how to programmatically compile a JavaScript file using a PHP class that talks directly to Google's compiler API.

Naturally, the API is capable of optimizing files through more advanced options; but as I said before, those will be explored in detail in forthcoming parts of the series. Meanwhile, feel free to edit all of the code samples included in this article; doing so will provide you with a more solid understanding of how to put the Closure Compiler Service API and PHP to work together.

Final thoughts

In this third part of the series, I developed a concrete example that illustrated how to use the Closure Compiler Service API for optimizing a JavaScript file via the set of PHP classes defined previously. In the earlier example, the level of optimization applied to the target file was basic, limited to stripping its white space and nothing else.

It's fair to note, though, that the API allows you to use more complex compiling algorithms in JavaScript files. To demonstrate how to achieve this, in the upcoming tutorial I'm going to set up another example that will perform a better optimization by assigning a different value to the pertinent "compilation_level" argument.

Don't miss the next part!



 
 
>>> More AJAX & Prototype Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
   

AJAX & PROTOTYPE ARTICLES

- Best AJAX Tutorials for Forms
- The Best AJAX Tutorials
- 8 Great Ajax Tutorials
- Using Ajax and jQuery
- Using Ajax and jQuery with HTML Forms
- Ajax.org Offers Cloud9 IDE for JavaScript
- Java Technologies Provider ICEsoft Releases ...
- Using Recaptcha in AJAX Prototype Framework ...
- Google's Closure Compiler Service API: Addit...
- Installing Google Web Toolkit: Introducing t...
- Google's Closure Compiler Service API: Displ...
- Google's Closure Compiler Service API: Deliv...
- Google's Closure Compiler Service API: the A...
- Google's Closure Compiler Service API: the S...
- Google's Closure Compiler Service API: Optim...

Developer Shed Affiliates

 



© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap

Dev Shed Tutorial Topics: