| home / programming / optimize / speedup / chap10 / 1 | [previous] |
|
By the same token, avoid multiple document.writes in favor of
one document.write of a concatenated string. So instead of this:
document.write(' string 1');
document.write(' string 2');
document.write(' string 3');
document.write(' string 4');
Do this:
var txt = ' string 1'+
' string 2'+
' string 3'+
' string 4';
document.write(txt);
NodeLists are lists of elements from object properties like .childNodes
and methods like getElementsByTagName(). Because these objects
are live (updated immediately when the underlying document changes), they
are memory intensive and can take up many CPU cycles. If you need a NodeList
for only a moment, it is faster to index directly into the list. Browsers
are optimized to access node lists this way. So instead of this:
nl = document.getElementsByTagName("P");
for (var i = 0; i < nl.length; i++) {
p = nl[i];
}
Do this:
for (var i = 0; (p = document.getElementsByTagName("P")[i]); i++)
In most cases, this is faster than caching the NodeList. In the second
example, the browser doesn't need to create the node list object.
It needs only to find the element at index i at that exact moment.
Object literals work like array literals by assigning entire complex data types to objects with just one command. So instead of this:
car = new Object();
car.make = "Honda";
car.model = "Civic";
car.transmission = "manual";
car.miles = 1000000;
car.condition = "needs work";
Do this:
car = {
make: "Honda",
model: "Civic",
transmission: "manual",
miles: 1000000,
condition: "needs work"
}
This saves space and unnecessary DOM references.
# # #
[Andy King is the founder and newsletter editor of WebReference.com. The companion Web site for this book can be found at: www.websiteoptimization.com.]
| home / programming / optimize / speedup / chap10 / 1 | [previous] |
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/5.html