AJAX - The Complete Reference

(avery) #1

268 Part II: Developing an Ajax Library^


nothing is gained in byte count since the semicolon added is equal to the return
saved, though in an environment where you have \r\n as a line break you would
gain a byte. Regardless of the potential lack of gain, it is certainly visually more
compressed.


  1. Perform code optimizations.
    Simple ideas like removing implied semicolons, var statements in certain cases, or
    empty return statements can help to further reduce some script code. Shorthand can
    also be employed in a number of situations, for example:


x=x+1;
can become:

x++;
However, be careful, as it is quite easy to break the code unless the optimizations
are very conservative.


  1. Rename user-defined variables and function names.


For good readability, any script should use variables like sumTotal instead of s.
However, for download speed, the lengthy variable sumTotal is a liability and
provides no user value, so s is a much better choice. Here again, writing your
source code in a readable fashion and then using a tool to prepare it for delivery
shows its value, since remapping all user-defined variable and function names to
short one- and two-letter identifiers can produce significant savings.


  1. Remap built-in objects.
    The bulkiness of JavaScript code, beyond long user variable names, comes from the
    use of built-in objects like Window, Document, Navigator and so on. For example,
    given code like:


alert(window.navigator.appName);
alert(window.navigator.appVersion);
alert(window.navigator.userAgent);

it could be rewritten as:

w=window;n=w.navigator;a=alert;
a(n.appName);
a(n.appVersion);
a(n.userAgent);
This certainly would apply to our friend XMLHttpRequest, which you might shorten to the
less tongue-twisting xhr:

xhr = xmlHttpRequest;

This type of remapping is quite valuable when objects are used repeatedly, which they
generally are. Note however, that if the window or navigator object were used only once,
these substitutions would actually make the code larger, so be careful if optimizing by hand.
Fortunately, many JavaScript code optimizers will take this into account automatically.
This tip brings up a related issue regarding the performance of scripts with remapped
objects: in addition to the benefit of size reduction, such remappings may actually slightly
Free download pdf