HTML and CSS Reference
In-Depth Information
Problem Solving: Speeding Up Your Access to the DOM
Manipulating the contents and structure of the node tree can slow down your programs,
especially for large and complicated document structures. There are several things you can
do to help speed up your code.
One core problem is reflow , which occurs when the Web browser must recreate the
content and layout of the entire Web document when any new content is added. To reduce
the amount of reflow, you should create all of your new content within a document frag-
ment and then attach the fragment at the end of your code so that the browser must reflow
the page only once. Avoid for loops in which the Web document is modified each time
through the loop. Instead, manipulate the document fragment each time through the loop
and then attach that fragment to the document once the loop has finished.
Another way to optimize your code is through the use of variables that reference specific
nodes. Rather than forcing the browser to navigate through a long and complicated node
tree, define a variable to reference a specific parent or child node within that tree. This
technique stores the location of that node in memory, freeing the browser from having to
locate it again the next time it is used.
Another place where the browser can be slowed down is in the creation of node lists
that reference collections of objects. Node lists can be memory intensive because the
browser must keep them updated as the Web document is modified. For example, the fol-
lowing code creates a node list named allP consisting of all paragraphs in the document:
var allP = document.getElementsByTagName(ā€œPā€);
for (var i = 0; i < allP.length; i++) {
thisP = allP[i];
You can optimize this code with the following for loop, which avoids the creation of this
node list:
for (var i = 0; (thisP = document.getElementsByTagName(ā€œPā€)[i]);
i++) {
The advantage is that the browser doesn't create a separate node list that will have to be
constantly updated and revised whenever the document changes. Instead, the browser
examines those nodes only within the context of the for loop. Once the loop is finished,
there is nothing for the browser to keep track of.
Used together, these techniques can speed up your program and make it operate more
efficiently, especially when manipulating the contents of long and complicated documents.
Search WWH ::

Custom Search