By Addy Osmani CHAPTER 6
paint and layout issues. Some of the core causes of jank in sites and appli-
cations include:
- Heavy paint times for your DOM elements.
- Unnecessary image resizes, because you haven’t pre-scaled to the
size you need. - Long image decodes (e.g. decoding PNG or JPEG).
- Unexpected layer invalidations.
- Garbage collector runs.
- Network requests (e.g. processing an XHR).
- Heavy animation or data processing.
- Input handlers with a heavy amount of JavaScript. One common
mistake is to add a lot of JavaScript to rearrange the page in an
onscroll handler which impacts paint times.
Faster Animations
requestanimationframe
setInterval and setTimeout are regularly used to create animations every
16ms. This comes with its own challenges, but two are of particular note:
refresh rates differ from device to device (e.g. the refresh rate on your
phone may not necessarily be the refresh rate on your desktop); and timer
resolution from JavaScript is only in the order of a few milliseconds.
For the next screen refresh to occur, you need a completed animation
frame with all JavaScript, DOM manipulation, painting and layout to be
ready. It can be really hard to get animation frames complete before the next
refresh when you’re working with low timer resolution and variations in
screen refresh rates make this near impossible with a fixed timer. Regardless
of what your timer interval is, you’ll eventually move out of your timing win-
dow for a frame and will drop them, meaning users may see a visual drop
in smoothness. You’ll also end up doing a bunch of work to generate frames
that never get shown, wasting critical battery and CPU time.