| home / programming / optimize / speedup / chap10 / 1 | [previous] [next] |
|
|
When you are adding complex content to your page (like a table), you will find it is faster to build your DOM node and all its sub-nodes offline before adding it to the document. So instead of this (see Listing 10.1):
var tableEl, rowEl, cellEl;
var numRows = 10;
var numCells = 5;
tableEl = document.createElement("TABLE");
tableEl = document.body.appendChild(tableEl);
for (i = 0; i < numRows; i++) {
rowEl = document.createElement("TR");
for (j = 0; j < numCells;j++) {
cellEl = document.createElement("TD");
cellEl.appendChild(document.createTextNode("[row "+i+" cell "+j+ "]"));
rowEl.appendChild(cellEl);
}
tableEl.appendChild(rowEl);
}
Do this (see Listing 10.2):
var tableEl, rowEl, cellEl;
var numRows = 10;
var numCells = 5;
tableEl = document.createElement("TABLE");
for (i = 0; i < numRows; i++) {
rowEl = document.createElement("TR");
for (j = 0; j < numCells;j++) {
cellEl = document.createElement("TD");
cellEl.appendChild(document.createTextNode("[row " +i+ " cell "+j+"]"));
rowEl.appendChild(cellEl);
}
tableEl.appendChild(rowEl);
}
document.body.appendChild(tableEl);
Listing 10.1 adds the table object to the page immediately after it is
created and adds the rows afterward. This runs much slower because the
browser must update the page display every time a new row is added. Listing
10.2 runs faster because it adds the resulting table object last, via
document.body.appendChild().
In a similar fashion, when you are manipulating subtrees of a document,
first remove the subtree, modify it, and then re-add it. DOM manipulation
causes large parts of the tree to recalculate the display, slowing things
down. Also, createElement() is slow compared to cloneNode().
When possible, create a template subtree, and then clone it to create
others, only changing what is necessary. Let's combine these two
optimizations into one example. So instead of this (see Listing 10.3):
var ul = document.getElementById("myUL");
for (var i = 0; i < 200; i++) {
ul.appendChild(document.createElement("LI"));
}
Do this (see Listing 10.4):
var ul = document.getElementById("myUL");
var li = document.createElement("LI");
var parent = ul.parentNode;
parent.removeChild(ul);
for (var i = 0; i < 200; i++) {
ul.appendChild(li.cloneNode(true));
}
parent.appendChild(ul);
By editing your subtrees offline, you'll realize significant performance
gains. The more complex the source document, the better the gain. Substituting
cloneNode instead of createElement adds an extra boost.
| home / programming / optimize / speedup / chap10 / 1 | [previous] [next] |
From Speed Up Your Site: Web Site Optimization, Chapter 10.
Copyright 2003. Reproduced by permission of New Riders.
Created: January 8, 2003
Revised: January 8, 2003
URL: http://webreference.com/programming/optimize/speedup/chap10/1/4.html