Online Book Reader

Home Category

AJAX In Action [145]

By Root 3966 0
If we are assembling a complex user interface, it therefore makes sense to create all the nodes and add them to each other and then add the assembled structure to the document. This way, the page layout process occurs once. Let’s look at a simple example of creating a container element in which we randomly place lots of little DOM nodes. In our description of this example, we referred to the container node first, so it seems natural to create that first. Here’s a first cut at this code: var container=document.createElement("div");

container.className='mousemat';

var outermost=document.getElementById('top');

outermost.appendChild(container);

for(var i=0;ivar node=document.createElement('div');

node.className='cursor';

node.style.position='absolute';

node.style.left=(4+parseInt(Math.random()*492))+"px"; node.style.top=(4+parseInt(Math.random()*492))+"px";

container.appendChild(node);

}

The element outermost is an existing DOM element, to which we attach our container, and the little nodes inside that. Because we append the container first and then fill it up, we are going to modify the entire document count+1 times! A quick bit of reworking can correct this for us:

var container=document.createElement("div");

container.className='mousemat';

var outermost=document.getElementById('top');

for(var i=0;ivar node=document.createElement('div');

node.className='cursor';

node.style.position='absolute';

node.style.left=(4+parseInt(Math.random()*492))+"px"; Licensed to jonathan zheng

294

CHAPTER 8

Performance

node.style.top=(4+parseInt(Math.random()*492))+"px";

container.appendChild(node);

}

outermost.appendChild(container);

In fact, we had to move only one line of code to reduce this to a single modification of the existing document. Listing 8.6 shows the full code for a test page that compares these two versions of the function using our stopwatch library. Listing 8.6 Profiling DOM node creation

profile 

 

®Online Book Reader