JavaScript Optimization Theory--Part 1 of Chapter 10 from Speed Up Your Site (5/5)--WebReference.com | WebReference

JavaScript Optimization Theory--Part 1 of Chapter 10 from Speed Up Your Site (5/5)--WebReference.com

To page 1To page 2To page 3To page 4current page
[previous]

Speed Up Your Site, Chapter 10: Optimizing JavaScript for Execution Speed

Concatenate Long Strings

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);

Access NodeLists Directly

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.

Use Object Literals

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.]


To page 1To page 2To page 3To page 4current page
[previous]

Created: January 8, 2003
Revised: January 8, 2003

URL: https://webreference.com/programming/optimize/speedup/chap10/1/5.html