Face Off: CSS vs JS Animation
Last week I talked with one of my friends who is a senior web developer and he was asking me some web animation questions.
And I found that many developers still have some confusions between the CSS and JS animation performance so I thought I should bring it up and share it with you.
CSS animation performs better than JS animation.
When someone says this statement, you should not agree with that, nor just disagree.
Because the statement above is more than just Yes or No question.
Long time ago, jQuery was introduced and our life became much easier in JS world. However, when it comes down to jQuery animation, our life becomes more complex and slower.
One of the biggest problems with jQuery animation is that it has no mechanism to avoid ‘Layout Thrashing’.
If you have read my previous article, changing layout is quite costly.
But due to its codebase, jQuery animation cannot avoid it.
If you want to find out more about how to avoid Layout Thrashing, check out this article:
Furthermore, jQuery animation needs to serve many purpose beyond animation, so its memory consumption triggers garbage collections in the browser and it causes animations to momentarily stutter.
So what you are still saying is CSS animation performs better than JS animation?
When you are comparing CSS animation with jQuery animation, the answer is YES.
Those JS libraries perform much better than CSS especially when you need to deal with huge number of elements at the same time.
You can compare the performance here:
Also the biggest benefit using JS library is you have many more options to control than CSS such as chaining, callback, promise etc.
So now you are saying JS animation performs better than CSS animation?
JS animation performs similar (sometimes better) level of CSS animation with more controls but they are JS based so when JS is disabled, the animation won’t work.
My suggestion is:
Use CSS animation when
- the animation is simple (e.g., button hover animation)
- the animation should work even if JS is disabled (e.g., loading bar)
Use JS animation when
- the animation requires a complex timeline
- the animation is not supported in CSS or works better with JS animation. For example, slideUp/Down is better and simpler with JS than CSS because with CSS, you need to set the max-height manually.
So now when someone asks if CSS animation performs better than JS animation, you have much more to talk about :)
Lastly, get inspired by this amazing animation (and nice music too):