Optimizing JavaScript for Download Speed
- When to Opt for Optimization
- Trim the Fat
- Apply JavaScripts Wisely
- Minimize HTTP Requests
- Abbreviate and Map
- Crunching and Obfuscation
- JavaScript and Compression
- Summary
A lightweight interpreted language, JavaScript is ideally suited to data validation, interactive forms, and enhancing navigation. Presented with such a broad toolset to play with, many authors have gone overboard with JavaScript, bulking up their sites at an alarming rate. Fortunately, JavaScript offers rich opportunities for file-size and execution-speed optimization. By using techniques like packing, compression, and obfuscation, you can realize 50 to 90 percent savings off the size of your JavaScript files. This chapter shows you how to put your JavaScripts on a low-char diet. In Chapter 10, "Optimizing JavaScript for Execution Speed," you will learn how to speed up the execution speed of your code.
Because JavaScript is part of web page content and not a standalone application, making your JavaScripts load quickly is important. The challenge is to find the right balance between size and speed, or between features and responsiveness.
When to Opt for Optimization
"The first principle of optimization is don't."1
Most JavaScripts are so fast and many are so small that they don't need to be optimized. First, code your scripts to work correctly and be self-describing by using the best algorithms and data structures you can. Then, if users start to notice a delay in loading or execution time, it's time to start thinking about optimization.
Larger, more complex scripts, such as cascading menus and expandable outlines, can benefit more from download speed than from execution speed optimization. Realistic interactive games and simulations can benefit more from execution speed than from file size optimization. As you'll discover in Chapter 10, you can trade size for speed complexity and vice versa. Optimizing both size and speed while maintaining legible code takes a combination of techniques.