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

(Joyce) #1

Since an optimization such as this entails changing the intention of your motion design,
this is not a technique that should always be employed. Consider it a last resort. If you
need to squeeze additional performance out of low-powered devices, then this technique
may be suitable. Otherwise, don’t pre-optimize the code on your site using techniques like
this, or you’ll end up with unnecessarily bloated and inexpressive code.


Technique: Don’t continuously react to scroll and resize events


Be mindful of how often your code is being run. A fast snippet of code being run 1,000
times per second may—in aggregate—no longer be very fast.


Problem


Browsers’ scroll and resize events are two event types that are triggered at very high
rates: when a user resizes or scrolls the browser window, the browser fires the callback
functions associated with these events many times per second. Hence, if you’ve registered
callbacks that interact with the DOM—or worse, contain layout thrashing—they can cause
tremendously high browser load during times of scrolling and resizing. Consider the
following code:


Click here to view code image
// Perform an action when the browser window is scrolled
$(window).scroll(function() {
// Anything in here is fired multiple times per second while the user
scrolls
});
// Perform an action when the browser window is resized
$(window).resize(function() {
// Anything in here is fired multiple times per second while the user
resizes
});
Recognize that the functions above aren’t simply called once when their respective
events start; instead, they are called throughout the duration of the user’s respective
interaction with the page.


Solution


The solution to this problem is to debounce event handlers. Debouncing is the process of
defining an interval during which an event handler callback will be called only once. For
example, say you defined a debounce interval of 250ms and the user scrolled the page for
a total duration of 1000ms. The debounced event handler code would accordingly fire
only four times (1000ms/250ms).


The code for a debounce implementation is beyond the scope of this book. Fortunately,
many libraries exist exclusively to solve this problem. Visit davidwalsh.name/javascript-
debounce-function for one example. Further, the tremendously popular Underscore.js
(UnderscoreJS.org), a JavaScript library akin to jQuery that provides helper functions for
making coding easier, includes a debounce function that you can easily reuse across your
event handlers.

Free download pdf