Main Page

Optimizing JavaScript

To this:
“He said, \\\”hi.\\\””
When this is output to JavaScript, you get a valid string:
<script type=”text/javascript”>
var sJavaScriptHeSaidHi = “He said, \”hi.\””;
This JavaScript code is syntactically correct and runs without error.
Use double quotes
Another common mistake is to use apostrophes to indicate strings instead of quotation marks. As you
remember, JavaScript allows either to represent strings, so the following two lines of code are equal:
sHello = “Hello”;
sHello = ‘Hello’;
Just because JavaScript lets you use either syntax doesn’t mean you can use them interchangeably when
you want internationalization. In fact, because apostrophes are much more common than quotation
marks in everyday language (especially in languages like French), you run into the same problem we
just explored with quotation marks, but far more often. Because of this, it’s considered best practice to
only use quotation marks to represent strings.
Following the guidelines in this section ensures that your internationalized JavaScript code works
Optimizing JavaScript
When creating desktop applications, most developers don’t need to think much about optimization. For
the most part, programming languages are optimized when they are compiled: All variables, functions,
objects, and so on, are replaced with symbolic pointers that are understood only by the processor.
Macros are compiled to be faster than function calls. Templates are used to speed up object creation. But
JavaScript is a very different animal because it’s downloaded as source code and then interpreted (not
compiled) by the browser. Because of this, the speed of JavaScript code is split into two categories:
download time and speed of execution.
Download time
When using Java or other such programming languages, developers need not give any thought to hav-
ing variable names that are 100 characters long because the names are all replaced; they need not worry
about writing paragraphs of comments because these, too, are removed. As a JavaScript developer, you
do not have this luxury.
Web browsers download JavaScript as source code, meaning that all long variable names and comments
are included. These and other factors increase the download time and thus increase the overall time it
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 573

JavaScript EditorFree JavaScript Editor     Ajax Editor