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:

Tags: api, compress, Google Tutorials & Articles, javascript
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 written more than 1,000 articles for SitePoint and you can find him @craigbuckler

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

No Reader comments

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.