AJAX In Action [145]
container.className='mousemat';
var outermost=document.getElementById('top');
outermost.appendChild(container);
for(var i=0;i 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;i 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