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

(Joyce) #1

Problem


You’re not done with gets and sets just yet! A common page set is the insertion of
new DOM elements at run-time. While there are many uses for adding new elements to a
page, perhaps the most popular is infinite scrolling, which consists of elements
continuously animating into view at the bottom of a page while the user scrolls downward.


As you learned in the previous section, browsers have to compute the composition of all
affected elements whenever a new element is added. This is a relatively slow process.
Hence, when DOM insertion is performed many times per second, the page is hit with a
significant performance impact. Fortunately, when processing multiple elements, browsers
can optimize page set performance if all elements are inserted at the same time.
Unfortunately, we as developers often unintentionally forgo this optimization by
separating our DOM insertions. Consider the following example of unoptimized DOM
insertion code:


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

Div 1
”, “
Div 2
”, “
Div
3
” ];
$newElements.each(function(i, element) {
$(element).appendTo($body);
// Other arbitrary code
});
This iterates through a set of element strings that are instantiated into jQuery element
objects (without a performance drawback since you’re not querying the DOM for each
JEO). Each element is then inserted into the page using jQuery’s appendTo().


Here’s the problem: even if additional code exists after the appendTo() statement,
the browser won’t compress these DOM sets into a single insertion operation because it
can’t be certain that asynchronous code operating outside the loop won’t alter the DOM’s
state between insertions. For example, imagine if you queried the DOM to find out how
many elements exist on the page after each insertion:


Click here to view code image
// Bad practice
$newElements.each(function(i, element) {
$(element).appendTo($body);
// Output how many children the body element has
console.log($body.children().size());
});
The browser couldn’t possibly optimize the DOM insertions into a single operation
because the code explicitly asks the browser to tell us the accurate number of elements
that exist before the next loop begins. For the browser to return the correct count each
time, it can’t have batched all insertions upfront.


In conclusion, when you perform DOM element insertion inside a loop, each insertion
happens independently of any others, resulting in a notable performance sacrifice.

Free download pdf