Day 2 – GPU accelerate your DOM elements

First up, we have a super simple way to improve the performance of animating DOM elements. You probably know that in CSS3 you can move divs and images around in 3D space, and when you do this, some browsers render them using the graphics hardware.

So that’s fine for moving things in 3D but how often do you need to do that? Hardly ever! Mostly you move things in 2D, and browsers do that with the slow software renderer. Boring!

But you can fool the browsers into thinking they’re rendering in 3D by setting the z position to 0 using translateZ :

transform : translateZ(0);

And of course you should use the browser specific prefixes too, so use the following css to speed up moving rotating and scaling any div :

div {
	-webkit-transform : translateZ(0); 
	-o-transform : translateZ(0); 
	-moz-transform : translateZ(0); 
	transform : translateZ(0); 

And in an extremely rare case of my helping Mr.doob rather than the other way around, this is exactly how he improved the performance on Google Gravity.

The good news – this works really well in WebKit browsers (especially mobile Safari on iOS), the even better news is that FireFox will GPU accelerate anything with a transform, so you don’t even need this little hack.

You can find out more about CSS 3D transforms in our Burst game tutorial.