How to Roll Your Own JavaScript Compressor with PHP and the Closure Compiler

Share this article

In my previous post, I discussed the Closure Compiler’s REST API. In this article, we’ll develop a small PHP program that shows how the API can be used to compress JavaScript code whenever you need it.

Why write your own system?

You’ll find that several free tools handle this task; one of the first PHP JavaScript compressors was written by Ed Eliot. Sometimes, however, they require technologies you don’t use — such as Java — or may not cater for internal workflow processes, including:
  • distributing uncompressed JavaScript to developer PCs
  • integration with source control systems
  • automating your build, and so on
Important: This is not production-level code!
The code below implements a rudimentary JavaScript compressor in PHP to illustrate the basics. The code calls the Closure Compiler compression API every time a request is made, so it’s likely to be slower than multiple uncompressed JavaScript files. You should add your own functions to handle caching to a file or database.

The HTML

Assume you normally include the following script tags at the bottom of your HTML:

<script src="script/file1.js"></script><script src="script/file2.js"></script><script src="script/file3.js"></script>

We’ll replace this block with a single script tag that references all three files.
The .js is removed and the file names are separated with an ampersand:

<script src="script/?file1&file2&file3"></script>

The PHP

We now require an index.php
file within our script folder. The first code block transforms the GET parameters into an array (file1, file2, file3) and initializes the variables:

<?php// fetch JavaScript files to compress$jsfiles = array_keys($_GET);$js = '';		// code to compress$jscomp = '';	        // compressed JS$err = '';	        // error string

We now loop through the JS files, read the content, and append it to the $js string. If a file is unable to be found or read, its name is appended to the $err string:

// fetch JavaScript filesfor ($i = 0, $j = count($jsfiles); $i < $j; $i++) {  $fn = $jsfiles[$i] . '.js';  $jscode = @file_get_contents($fn);  if ($jscode !== false) {    $js .= $jscode . "n";  }  else {    $err .= $fn . '; ';  }}

If any files are missing, we can generate a JavaScript alert to inform the developer:

if ($err != '') {  // error: missing files  $jscomp = "alert('The following JavaScript files could not be read:\n$err');";}

If there are no errors and we have some JavaScript code, we can proceed with the compression. The $apiArgs array contains a list of Closure Compiler API options — you can add, remove, or modify these as necessary. The arguments are encoded and appended to the $args string:

else if ($js != '') {  // REST API arguments  $apiArgs = array(    'compilation_level'=>'ADVANCED_OPTIMIZATIONS',    'output_format' => 'text',    'output_info' => 'compiled_code'   );   $args = 'js_code=' . urlencode($js);   foreach ($apiArgs as $key => $value) {     $args .= '&' . $key .'='. urlencode($value);   }
We can now call the Closure Compiler API using PHP’s cURL library. The compressed JavaScript is returned to the $jscomp string:

  // API call using cURL  $call = curl_init();  curl_setopt_array($call, array(    CURLOPT_URL => 'http://closure-compiler.appspot.com/compile',    CURLOPT_POST => 1,    CURLOPT_POSTFIELDS => $args,    CURLOPT_RETURNTRANSFER => 1,    CURLOPT_HEADER => 0,    CURLOPT_FOLLOWLOCATION => 0  ));  $jscomp = curl_exec($call);  curl_close($call);

Finally, we return our compressed code to the browser with the appropriate MIME type:
}// output content header('Content-type: text/javascript'); echo $jscomp; ?> 

Download the Code

Save yourself some typing and download the example code. It includes a small JavaScript library shrunk to a third of its original size, and incurs fewer HTTP requests.

Over to You …

You can now adapt this basic code to implement features such as:
  • Error handling — Your code should check for API call failures or compression problems reported by the Closure Compiler.
  • Caching — Once you have the compressed code you can save it to a file, so there’s no need to repeatedly call the API. You could compare creation dates to check whether a JavaScript file has changed since it was last cached.
  • Browser caching — HTTP expiry headers can be set so that compressed JavaScript files are cached by the browser indefinitely. You could add a “last-updated” argument to the script tag URL to ensure more recent code is always loaded.
  • JavaScript code reports — The Closure Compiler API can be used to highlight problems not reported by browser parsers; for example, unused variables or a comma after the final item in an array.
  • Build processes — Your system could distribute uncompressed JavaScript code to a developer and compressed code to everyone else.
I hope you find it useful. Will you use the Closure Compiler API to automate your JavaScript compression processes? Respond via the blog entry link below.

Frequently Asked Questions about JavaScript Compression with PHP

What is JavaScript compression and why is it important?

JavaScript compression, also known as minification, is the process of removing unnecessary characters from the source code without changing its functionality. This includes white spaces, new line characters, comments, and block delimiters which are useful for us humans but not necessary for machines. The importance of JavaScript compression lies in its ability to reduce the size of the JavaScript files, which in turn reduces the amount of data that needs to be transferred over the network. This can significantly improve the load time and performance of a website, leading to a better user experience.

How does PHP help in JavaScript compression?

PHP, being a server-side scripting language, can be used to automate the process of JavaScript compression. It can read the original JavaScript file, remove all unnecessary characters, and then output the compressed version. This can be particularly useful when you have a large number of JavaScript files as it can save a lot of manual work.

What are the best practices for JavaScript compression with PHP?

When compressing JavaScript with PHP, it’s important to keep a few best practices in mind. First, always keep a backup of the original JavaScript file. This is because once the file is compressed, it becomes very difficult to read and modify. Second, use a reliable PHP script or library for compression. There are many available online, some of which offer additional features like error checking and compatibility fixes. Finally, test the compressed JavaScript file thoroughly before deploying it. This is to ensure that the compression process has not introduced any errors or bugs.

Are there any tools available for JavaScript compression?

Yes, there are many online tools and libraries available for JavaScript compression. These tools can automatically remove all unnecessary characters from your JavaScript files, resulting in a smaller file size. Some popular tools include JSCompress, JavaScript Minifier, and UglifyJS. There are also PHP libraries available that can automate this process, such as JShrink and Minify.

Can JavaScript compression affect the functionality of my website?

If done correctly, JavaScript compression should not affect the functionality of your website. The purpose of compression is to remove unnecessary characters, not to alter the actual code. However, it’s always a good idea to thoroughly test your website after compression to ensure everything is working as expected.

How can I ensure the best performance after JavaScript compression?

After compressing your JavaScript files, it’s important to ensure they are being served with gzip compression. This is a server-side compression technique that can further reduce the size of your JavaScript files. Also, make sure your server is configured to send the correct ‘Content-Encoding’ header to tell the browser that the files are compressed.

What is the difference between JavaScript compression and obfuscation?

While both JavaScript compression and obfuscation can reduce the size of your JavaScript files, they serve different purposes. Compression is about removing unnecessary characters to improve load times and performance. Obfuscation, on the other hand, is about making the code difficult to read and understand in order to protect it from unauthorized access and modification.

Can I compress other types of files with PHP?

Yes, PHP can be used to compress other types of files as well. This includes CSS files, HTML files, and even images. The process is similar to JavaScript compression, where unnecessary characters are removed to reduce the file size.

Is JavaScript compression necessary for all websites?

While JavaScript compression is not strictly necessary for all websites, it is highly recommended for websites with large JavaScript files or high traffic. By reducing the size of your JavaScript files, you can significantly improve the load time and performance of your website, leading to a better user experience.

Can I compress JavaScript files manually?

Yes, it’s possible to compress JavaScript files manually by removing all unnecessary characters. However, this can be a time-consuming and error-prone process, especially for large files. Using a PHP script or an online tool can automate this process and ensure a more reliable result.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

apicompressjavascriptPHP
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week