Skip to main content

Easy JavaScript Compression with the Closure Compiler REST API

By Craig Buckler



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

The days of tiny JavaScript files are long gone. Today’s monolithic web applications contain client-side code running to thousands of lines. Browsers and download speeds may have improved, but optimizing JavaScript has become increasingly important. The techniques adopted by professional developers include:

  1. Placing script tags at the end of the HTML body so the content appears quickly and is not delayed by code loading and execution.
  2. Reducing HTTP requests by merging multiple JavaScript files into one.
  3. Reducing JavaScript file sizes by removing unnecessary whitespace, shortening variable names, and running other optimizations.

There are several JavaScript compression libraries and online tools to help you shrink your code. However, steps 2 and 3 often remain a manual process for many developers.

If you’re fed up with manual JavaScript compression, you’ll be pleased to hear Google’s Closure Compiler recently added a REST API. You can now call a web service to compress JavaScript — there’s no code to install or maintain.

The API makes it easy for developers to create their own JavaScript merging and compression system. For example, you could:

  • generate reports highlighting code errors and warnings. The API can check for problems which are not normally reported by browsers such as unused variables or a comma after the final item in an array.
  • distribute uncompressed code to application developers
  • compress code for testers and end users
  • implement version control mechanisms
  • integrate compression into your build when updating the live system.

Not sure where to start? Read my next post — How to Roll Your Own JavaScript Compressor with PHP and the Closure Compiler

For more information, refer to:

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.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.