Home arrow AJAX & Prototype arrow Page 2 - Google's Closure Compiler Service API: Delivering Compiled Code in Different Formats

Returning compiled JavaScript code as XML - AJAX

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.

TABLE OF CONTENTS:
  1. Google's Closure Compiler Service API: Delivering Compiled Code in Different Formats
  2. Returning compiled JavaScript code as XML
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
October 12, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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!



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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

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

 


Dev Shed Tutorial Topics: