Google’s Closure Compiler Service API: Delivering Compiled Code in Different Formats

In this sixth part of the series, I explore Google’s Closure Compiler Service API’s “output_format” argument. It permits you to deliver compiled JavaScript code to the client in different formats, including the already familiar “text/javascript” type. I also show you how to deliver code in XML and JSON formats.

As you know, in the last few years Google has branched out from its core search engine service. It has launched a bunch of web services, aimed, at least in theory, at making the life of web developers and designers a bit easier. This time the company has put its effort into the client side by implementing a brand new service called Closure Compiler Service API. This service allows you to optimize custom JavaScript code through a set of easily configurable options that must be passed to the API via POST HTTP requests.

Quite possibly, the most interesting facet of this service is that it can be consumed by using any popular programming language, including PHP. This ability permits you to compile JavaScript snippets programmatically without having to spend valuable time performing this task manually via a graphic user interface (usually an HTML form).

To demonstrate how simple it is to interact with the Closure Compiler Service API via a PHP backend, in previous installments of this series I created some basic examples that showed how to apply different levels of optimization to a specified JavaScript file by assigning distinct values to the API’s “compilation_level” argument. This process revealed that the compiler is capable of doing some useful tasks behind the scenes, such as removing comments and white space from target JavaScript files, shortening function and variable names, and even refactoring large chunks of code.

Moreover, the Closure Compiler Service API also has the ability to return compiled code in different formats, including the familiar “text/javascript” content type, XML and JSON. If you’re interested in learning how to accomplish this, in this sixth part of the series I’m going to set up a few easy-to-grasp code samples that will illustrate how to return compiled JavaScript code in the formats mentioned above.

Ready to continue learning about Google’s Closure Compiler Service API? Then  start reading!

Creating a “standard” example: returning compiled JavaScript in “text/javascript” format

As I explained in the introduction, the Closure Compiler Service API is capable of delivering compiled JavaScript code in three different formats: the default “text/javascript” type, XML and JSON. In case you’re wondering how to achieve this, the content type generated by the compiler can be easily controlled by assigning different values to its “output_format” argument. It’s that simple.

Having explained that, the first example that I plan to show you returns compiled code using a mixture of text and JavaScript. Here it is:

<?php

// example using output_format = text
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’ => ‘ADVANCED_OPTIMIZATIONS’,
         ‘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;
    /*
    displays the following
   
 var a=document.createElement("div");a.setAttribute("id","divid");a.setAttribute("class","divclass");document.getElementsByTagName("body")[0].appendChild(a);
    */  
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

Admittedly, the code sample shown above looks very similar to others developed in previous parts of this series. It sends back to the client compiled code in the format of text and JavaScript, so the “ClosureCompilerHandler” class also includes the appropriate “Content-type: text/javascript” MIME header, before echoing the output to the browser.

At this point, I’m certain that you’ve already grasped the logic that drives the previous example. It simply assigns the value “text” to the “output_format” argument passed to the Closure Compiler Service API. As I explained before, though, the API can also be instructed to return compiled code in XML and JSON as well.

In the next segment I’m going to create another example. It will utilize the aforementioned “output_format” argument to return optimized JavaScript code as XML.

Want to see how this will be done? Then click on the link below and keep reading.    

{mospagebreak title=Returning compiled JavaScript code as XML}

As you may already have guessed, delivering compiled JavaScript code in XML is a process reduced to assigning the value “xml” to the “output_format” argument taken by the Closure Compiler Service API and nothing else.

Below I’ve included a brand new code snippet to drive this point home. It shows how to convert optimized JavaScript code to XML by tweaking the aforementioned argument. Check it out:

<?php

// example using output_format = xml
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’ => ‘ADVANCED_OPTIMIZATIONS’,
         ‘output_format’ => ‘xml’,
         ‘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(‘xml’);
    // print to screen the compiled JavaScript function in XML
    echo $response;
    /*
    displays the following

    <compilationResult>
        <compiledCode>
            var a=document.createElement("div");a.setAttribute("id","divid");a.setAttribute("class","divclass");document.getElementsByTagName("body")[0].appendChild(a);
        </compiledCode>
    </compilationResult>
    */  
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

Definitely, you’ll have to agree with me that the previous example is very easy to follow, right? As you can see, once the corresponding “output_format” argument has been passed to the API with a value of “xml,” the compiler has effectively returned the optimized code in XML format. Also, you should notice that the code has been wrapped inside of a couple of tags called <compilationResult> and <compiledCode>, so be careful of these elements, especially if you need to apply some form of additional processing to the output once it has been returned to the client.

So far, so good. Having explained in detail how make the Closure Compiler Service API return optimized code in XML, the next step is to discuss how to instruct the compiler to deliver the processed output in JSON format.

Still not sure how to achieve this? Well, to find the answer, read the following lines.  

Going one step further: serving compiled code in JSON format

The only thing we need to do to return compiled code in JSON format is assign the value “json” to the “output_format” argument accepted by the Closure Compiler Service API. To shed some light on how to achieve this, I included an amended version of the example created in the previous segment, which this time sends the optimized JavaScript back to the client as a JSON object. Here it is: 

<?php

// example using output_format = json
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’ => ‘ADVANCED_OPTIMIZATIONS’,
         ‘output_format’ => ‘json’,
         ‘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(‘json’);
    // print to screen the compiled JavaScript function in JSON format
    echo $response;
    /*
    displays the following
    {"compiledCode":"var au003ddocument.createElement("div");a.setAttribute("id","divid");a.setAttribute("class","divclass");document.getElementsByTagName("body")[0].appendChild(a);"}
    */  
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

As the above snippet shows, the assignment of the value “json” to the “output_format” option has obligated the compiler to return the optimized JavaScript in the form of a simple JSON object, whose key is identified as “compiledCode,” and its value is not surprisingly the optimized output itself. That was pretty simple to understand, wasn’t it?

While the examples that you just saw demonstrate that the Closure Compiler Service API yields quite satisfactory results when it comes to delivering compiled JavaScript in different formats, most likely you’ll be using the default “text/javascript” type. Nevertheless, if you’re used to building web applications that deal with XML or JSON encoded data, you might find the options discussed before pretty helpful. 

Final thoughts

That’s all for the moment. Over the course of this sixth part of the series, I explored another useful feature provided by Google’s Closure Compiler Service API, which through its “output_format” argument permits you to deliver compiled JavaScript code to the client in different formats, included the already familiar “text/javascript” type, then XML and finally JSON.

Needless to say, it’s possible to return optimized code in formats other than the ones mentioned above (for instance, you might want to embed the compiled output into a PDF document for display purposes). In a case like this, you’ll have to first grab the corresponding output and generate the PDF file by using a third-party library like PDFlib (http://pecl.php.net/package/pdflib), or a similar package. Possibilities are endless.

Moving on, it’s time to speak of the topics that I plan to discuss in the upcoming episode. As you may have already noticed in all of the examples developed so far, the Closure Compiler Service API takes an argument called “output_info,” which is used to tell the compiler what kind of output must be returned to the client.

In all of the aforementioned examples, the value assigned to this argument was “’compiled_code,” which makes the compiler deliver exactly that: the compiled JavaScript. It’s feasible, however, to return distinct information, such as the errors and warnings generated during the compiling process by tweaking the argument in question. Given that possibility, in the next tutorial I’m going to build a few additional examples that will show how to play with the “output_info” parameter in a truly painless fashion.

Here’s my final piece of advice: don’t miss the next part!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort