$(“element”)..style.left = currentLeft + 1; // Set
If you rewrite the code so that all queries and updates are aligned, the browser can batch
the respective actions and reduce the extent to which this code causes layout trashing:
Click here to view code image
var currentTop = $(“element”).css(“top”); // Get
var currentLeft = $(“element”).css(“left”); // Get
$(“element”).css(“top”, currentTop + 1); // Set
$(“element”).css(“left”, currentLeft + 1); // Set
The illustrated problem is commonly found in production code, particularly in
situations where UI operations are performed depending on the current value of an
element’s CSS property.
Say your goal is to toggle the visibility of a side menu when a button is clicked. To
accomplish this, you might first check to see if the side menu has its display property
set to either "none" or "block", then you’d proceed to alternate the value as
appropriate. The process of checking for the display property constitutes a get, and
whichever action is subsequently taken to show or hide the side menu will constitute a
set.
The optimized implementation of this code would entail maintaining a variable in
memory that’s updated whenever the button is clicked, and checking that variable for the
side menu’s current status before toggling its visibility. In this way, the get can be
skipped altogether, which helps reduce the likelihood of the code producing a set
alternated with a get. Further, beyond reducing the likelihood of layout thrashing, the UI
now also benefits from having one less page query. Keep in mind that each set and get
is a relatively expensive browser operation; the fewer there are, the faster your UI will
perform.
Many tiny improvements ultimately add up to a substantial benefit, which is the
underlying theme of this chapter: Follow as many performance best practices as you can,
and you’ll wind up with a UI that rarely sacrifices your desired motion design goals for
the sake of performance.
jQuery Element Objects
Instantiating jQuery element objects (JEO) is the most common culprit of DOM gets.
You may be wondering what a JEO is, but you’ve certainly seen this code snippet before:
Click here to view code image
$(“#element”).css(“opacity”, 1);
... or its raw JavaScript equivalent:
document.getElementById(“element”).style.opacity = 1;
In the case of the jQuery implementation, the value returned by $("#element") is a
JEO, which is an object that wraps the raw DOM element that was queried. JEO’s provide
you with access to all of your beloved jQuery functions, including .css(),
.animate(), and so on.
In the case of the raw JavaScript implementation, the value returned by
getElementByid("element") is the raw (unwrapped) DOM element. In both