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

Google's Closure Compiler Service API: Optimizing a JavaScript File

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

In consonance with its typical diversification, this time Google has put its effort into a field other than search engines recently by launching a brand new web service. Called Closure Compiler Service API , it allows developers to optimize JavaScript files by using a set of easily customizable options. Moreover, the service can be consumed manually via a graphical user interface, or programmatically by using any server-side programming language, like PHP, Python, Ruby and so forth.

By far, the most interesting facet of the new optimization service provided by Google is its ability to be queried directly from within a web application. This process permits you to compile JavaScript files on the fly, which can be cached later on.

To elaborate further on this concept, in the two articles that preceded this one I started building a simple PHP-based back end which was made up of two basic classes. The first one was an abstract parent responsible for handling HTTP requests at a very generic level, while the second class was a refined implementation of the parent, tasked with interacting specifically with the Closure Compiler Service API.

With these two classes already up and running, it's time to begin demonstrating how to use them for optimizing some sample JavaScript files. In this third part of the series I'm going to create an introductory example that will employ the aforementioned classes (and a few more) to compile a single JavaScript file via Google's API.

Does my proposal sound appealing enough to you? Then keep reading!

Giving the final touches to previous PHP-based back end: adding a couple of sample classes    

As I said in the introduction, my plan is simply to show you how to consume the Closure Compiler Service API from within a PHP-based application. But before I reach that point, it's necessary to add a couple of additional classes to the back end created previously. The first of these extra classes will be called "FileHandler." It will be charged with reading and writing data to a specified file. Its corresponding definition is as follows:  

(FileHandler.php)

<?php

class FileHandler
{
    protected $_path = 'function.js';
    protected $_data;
   
    // constructor
    public function __construct($path = '')
    {
        if ($path !== '') {
            $this->setPath($path);
        }
    }
   
    // set the path to read/write data
    public function setPath($path)
    {
        if (!file_exists($path)) {
            throw new FileHandlerException('The specified path is not valid.');
        }
        $this->_path = $path;
    }
   
    // get the specified path
    public function getPath()
    {
        return $this->_path;
    }
   
    // set new data to be written
    public function setData($data)
    {
        $this->_data = $data;
    }
   
    // get the stored data
    public function getData()
    {
        return $this->_data;
    }
       
    // read data from the specified path
    public function read()
    {
        if (!$this->_data = file_get_contents($this->_path)) {
            throw new FileHandlerException('Error reading from the target file.');
        }
        return $this->_data;
    }
   
    // write data to the specified path
    public function write($data)
    {
        if (!file_put_contents($this->_path, $data)) {
            throw new FileHandlerException('Error reading from the target file.');
        }
        $this->_data = $data;
    }           
}


    
<?php

class FileHandlerException extends Exception{}

As you can see, the above "FileHandler" class behaves like a simple wrapper for the "file_get_contents()" and "file_put_contents()" PHP native functions, which permit you to write and read data from a given file. The reason to code such a class is merely to read a given JavaScript file via a clean object-oriented interface. Keep in mind, however, that identical results can be obtained by using procedural code, so stay procedural if you're more comfortable with this approach.

Having defined the previous file handler, the only thing we need to do is create an autoloader that lazy-loads classes using the PHP SPL stack. In this case, the "Autoloader" class shown below performs that task pretty simply. Check it out:

(Autoloader.php)

<?php

class Autoloader
{
    private static $_instance;
   
    // get the Singleton instance of the autoloader
    public static function getInstance()
    {
        if (!self::$_instance) {
            self::$_instance = new self;
        }
        return self::$_instance;
    } 
   
    // constructor
    private function __construct()
    {
        spl_autoload_register(array($this, 'load'));
    }
   
    // prevent cloning instance of the autoloader
    private function __clone(){}
   
    // load a given class or interface
    public static function load($class)
    {
        $file = $class . '.php';
        if (!file_exists($file)) {
            throw new ClassNotFoundException('The file containing the requested class or interface ' . $class . ' was not found.');
        }
        require $file;
        unset($file);
        if (!class_exists($class, FALSE) AND !interface_exists($class, FALSE)) {
            throw new ClassNotFoundException('The requested class or interface ' . $class . ' was not found.');
        }
    }  
}

 

<?php

class ClassNotFoundException extends Exception{}

As I just said, the previous "Autoloader" class is responsible for loading classes on demand by using the built-in autoloading mechanism included with PHP 5. Again, it's valid to note that the implementation of this autoloader is entirely optional and can be skipped, especially if you're used to working with multiple PHP includes instead. You've been warned!

So far, so good. Having defined the two previous classes, the scenario is finally set to start testing the actual functionality of the Closure Compiler Service API when invoked from inside a PHP application. Therefore, in the following segment I'm going to build a sample JavaScript file, which will be passed to the API so it can be optimized.

To see how this sample file will be created, click on the link below and keep  reading.



 
 
>>> 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: