Summary
The easiest way to optimize JavaScript is to avoid the need for it in the first place. First, trim the fat by deleting unnecessary scripts and features. To avoid being featured in an accessibility story, use JavaScript only to enhance the user experience, not to create it. Email validation, responsive pop-up menus, and more can be created without the need for optimization. For larger projects where size or speed is an issue, optimization makes more sense.
Because JavaScript must be downloaded, make sure that your code is optimized for size and grouped to minimize HTTP requests. Many a site has added fancy navigational gizmos that are slow to load, because of many small (and not so small) files, each taking an indeterminate amount of time to download. Embed shorter scripts on high-traffic pages for maximum speed.
Automated packing programs can remove white space and comments, and some can abbreviate names. For maximum control, however, abbreviate your object and variable names manually. Where possible, defer program execution and loading, and compress larger scripts located in the head. Here's a list of the techniques you learned in this chapter:
Trim the fat by removing excess whitespace and comments, and using semicolons to avoid any misunderstandings.
Minimize HTTP requests by combining files and merging or embedding scripts on high traffic pages.
Defer or delay loading where possible (but avoid sticky pages).
Load only what's necessarysegment API code (NS4, IE5, DOM, and so on).
Compress larger external files located in the head.
Gracefully degradeavoid JavaScript-only techniques.
Abbreviate and map names automatically or manually to make your optimization reversible.
Crunch and obfuscate your code to shrink scripts and deter prying eyes.
Create self-extracting archives if entering the 5K competition.
Use ESC or Blue Clam to abbreviate variable and object names for maximum packing.
Further Reading
JavaScript: The Definitive Guide, 4th ed. by David Flanagan (O'Reilly, 2001).
Programming Pearls, 2nd ed. by Jon Bentley (Addison-Wesley, 1999)See Column 10: "Squeezing Space."
http://www.ecma.chThe ECMAScript Standards.
http://www.javascript.comThe definitive JavaScript resource. News, views, and how-tos.
http://directory.google.com/Top/Computers/Programming/Languages/JavaScript/Open Directory JavaScript Resources.