Main Page

Other ways to decrease the byte count

One of the best tools for JavaScript code minimizing and variable replacement is the ECMAScript Cruncher
(ESC) by Thomas Loo (available from Saltstorm at
http://www.saltstorm.net/depo/esc/
). ESC is a
small Windows Shell Script that can do all the optimizations mentioned in this section for you.
To run ESC, you must be using a Windows. Open up a console window and use the following format:
cscript ESC.wsf -l [0-4] -ow outputfile.js inputfile1.js [inputfile2.js]
The first part,
cscript
, is the Windows Shell Script interpreter. The filename
ESC.wsf
is the ESC pro-
gram itself. After that is the crunch level, which is a number between
0
and
4
, indicating which opti-
mizations should be applied. The
–ow
option indicates that the next argument is the output file for the
optimization. Finally, all remaining arguments are the JavaScript files to optimize. You can specify only
one file to optimize or multiple files (which are optimized and placed into the output file one after the
other).
The four levels of optimization supported by ESC are explained in the following table:
Level
Description
0
Leaves the script as-is. This is valuable if you want to append multiple files into a
single file.
1
Removes all comments.
2
Save as level 1, plus removes extra tabs and spaces.
3
Save as level 2, plus removes line breaks.
4
Save as level 3, plus replaces variable names.
ESC is very good at replacing variable names with nonsense names. It also is intelligent enough to
replace private object properties and methods (those denoted with two underscores at the beginning and
end of the name) with nonsense names, so your private properties and methods stay private.
ESC leaves your constructor names, public properties, and public methods intact, so no need to worry
about those. The only thing to keep in mind when using ESC is that if the JavaScript file references a
constructor in another file (such as the
StringBuffer
class from earlier in the book), crunching at level
4 replaces the references to this constructor with a nonsense name. The solution is to crunch both files
into a single file, thus retaining the constructor name.
Other ways to decrease the byte count
The following are suggestions to optimize scripts for size using somewhat uncommon methods that
save a lot of bytes. These suggestions aren’t handled by ESC, so you must carry them out by hand.
Replace Boolean values
You learned early on that for comparison purposes,
true
is equal to
1
and
false
is equal to
0
. Therefore,
anytime a script contains the literal value
true
, it can be replaced with a
1
and anytime a script contains
false
, it can be replaced with a
0
. This saves three bytes in the case of a
true
and four bytes in the case of
a
false
, but it doesn’t alter the meaning of any Boolean expression.
576
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 576


JavaScript EditorFree JavaScript Editor     Ajax Editor


©