CHAPTER 6 Finding and Fixing Mobile Web Rendering Issues
You may have noticed that we’ve been caring about frame rate so far
when talking about rendering performance — variance has the potential
to be a larger issue because, as I mentioned, our eyes notice those little
glitches in motion and these tend to come with poorly timed animations.
The best way to get accurate timed animation frames is to use the
requestAnimationFrame API, currently supported in all modern browsers.
When you use it, you ask the browser to give you an animation frame and
your callback gets called when it’s going to generate a new frame. This hap-
pens irrespective of the device’s refresh rate — which is awesome.
Tom Wiltzius^11 and Paul Lewis^12 have written on HTML5Rocks about
animation optimization with requestAnimationFrame more succinctly than
I could, and they’ve also previously pointed out some of the other nice things
it gives you that are quite relevant to mobile. For example, animations in
background tabs get paused, which can conserve your battery life, and if the
device can’t render at the screen’s refresh rate it can actually throttle ani-
mations and just generate the callback a little less regularly (e.g. 30 times a
second rather than 60). Although this might mean you’re halving your frame
rate, it means your animation stays consistent. A constant lower frame rate
is better than a varied 60Hz that drops some of its frames.
CSS aniMaTion
We’ve talked about requestAnimationFrame, but did you know that even
more efficient than lighter JavaScript animation in your callbacks is no
JavaScript at all? There’s no perfect solution for avoiding interruptions in
requestAnimationFrame callbacks, but you can get some mileage using CSS
animations to remove the need for them. In browsers like Opera Mobile
and Chrome for Android, CSS animations can be run by the browser while
JavaScript is running thanks to multi-threading.
11 http://www.html5rocks.com/en/tutorials/speed/rendering/
12 http://www.html5rocks.com/en/tutorials/speed/animations/