Main Page

Use the DOM sparingly

Use array and object literals
I mentioned doing this to decrease byte count, but you can also replace array and object definitions with
literals to decrease execution time. Consider the following object definition:
var oFruit = new Object;
oFruit.color = “red”; = “apple”;
As mentioned previously, the previous code can be rewritten using an object literal:
var oFruit = { color: “red”, name: “apple” };
Besides the decrease in byte count, the object literal is one statement whereas the extended syntax is
three statements; one statement is always executed faster than three. The same effect can be achieved
using array literals instead of the extended array syntax.
Use the DOM sparingly
One of the most time-intensive operations in JavaScript is DOM manipulation. Anytime you add,
remove, or otherwise change the underlying DOM structure of a page, you are incurring a significant
time penalty. This happens because every DOM manipulation alters the appearance of the page to a
user, meaning that the entire page must be recalculated to ensure that the page is rendered properly.
The way to get around this problem is to do as many DOM manipulations as possible with elements
that aren’t already in the DOM document.
Consider the following example that adds 10 items to a bulleted list:
var oUL = document.getElementById(“ulItems”);
for (var i=0; i < 10; i++) {
var oLI = document.createElement(“li”);
oLI.appendChild(document.createTextNode(“Item “ + i));
Two problems arise with this code in terms of execution speed. The first is the
at the middle of the loop. Each time through, this line executes and the entire page must be recalculated
to allow for the item to be updated. The second problem is the following line that adds the text node to
the list item, which also causes page recalculation. With these two problems, every trip through the loop
causes two page recalculations for a total of 20.
To fix this problem, the list items should not be added until after the text nodes have been assigned.
Additionally, you can use a document fragment to hold all the created list items until it’s time to add
them to the list:
var oUL = document.getElementById(“ulItems”);
var oFragment = document.createDocumentFragment();
for (var i=0; i < 10; i++) {
var oLI = document.createElement(“li”);
oLI.appendChild(document.createTextNode(“Item “ + i));
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 592

JavaScript EditorFree JavaScript Editor     Ajax Editor