Web Animation using JavaScript: Develop & Design (Develop and Design)

(Joyce) #1

Solution


Instead of individually inserting new elements into the DOM, construct the full DOM
element set in memory, then insert it via a single call to appendTo(). The optimized
version of the code shown in the section above now looks like this:


Click here to view code image
// Optimized
var $body = $(“body”);
var $newElements = [ “

Div 1
”, “
Div 2
”, “
Div
3
” ];
var html = ””;
$newElements.each(function(i, element) {
html += element;
});
$(html).appendTo($body);
This concatenates the string representation of each HTML element onto a master string
that is then turned into a JEO and appended into the DOM in a single shot. In this way, the
browser is given explicit instruction to insert everything at once, and it optimizes for
performance accordingly.


Simple, right? As you’ll see in the remainder of this chapter, performance best practices
are usually as easy as this. You simply have to train your eye to know when to use them.

Free download pdf