implementations, the browser is instructed to search through the DOM tree to find the
desired element. This is an operation that, when repeated in bulk, impacts page
performance.
This performance concern is exacerbated when uncached elements are used in code
snippets that are repeated, such as the code contained by a loop. Consider the following
example:
Click here to view code image
$elements.each(function(i, element) {
$(“body”).append(element);
});
You can see how $("body") is a JEO instantiation that’s repeated for every iteration
of the $.each() loop: In addition to appending the loop’s current element to the DOM
(which has its own performance implications), you’re now also repeatedly forcing a DOM
query. Seemingly harmless one-line operations like these add up very quickly.
The solution here is to cache the results—or, save the returned JEO’s into variables—to
avoid a repeated DOM operation every time you want to call a jQuery function on an
element. Hence, the code goes from looking like this:
Click here to view code image
// Bad practice: We haven’t cached our JEO
$(“#element”).css(“opacity”, 1);
// ... some intermediary code...
// We instantiate the JEO again
$(“#element”).css(“opacity”, 0);
to looking like this after it’s properly optimized:
Click here to view code image
// Cache the jQuery element object, prefixing the variable with $ to indicate
a JEO
var $element = $(“#element”);
$element.css(“opacity”, 1);
// ... some intermediary code...
// We re-use the cached JEO and avoid a DOM query
$element.css(“opacity”, 0);
Now you can reuse $element throughout your code without ever incurring a repeated
DOM lookup on its behalf.
Force-feeding
Traditionally, animation engines query the DOM at the start of an animation to determine
the initial value of each CSS property being animated. Velocity offers a workaround to this
page-querying event through a feature called force-feeding. It’s an alternative technique
for avoiding layout thrashing. With force-feeding, you explicitly define your animations’
start values so that these upfront gets are eliminated.
Force-fed start values are passed in as the second item in an array that takes the place of
a property’s value in an animation properties map. The first item in the array is the
standard end value that you’re animating toward.