Which is Faster – CSS or JS animation?

Have you ever noticed how animations based on JavaScript have been faster than CSS transitions always? Moreover, how can Google and Adobe keep releasing mobile sites, which are rich in media, and give tough competition to native apps in terms of performance?

 

In this article we will explore step by step how DOM animation libraries based on JavaScript, such as GSAP and Velocity.js, are better in performance than CSS and jQuery transitions.

 

jQuery

 

We will begin with basics: combining jQuery and JavaScript is not right and this is because jQuery, being slow, affects JavaScript animation as well, which is faster. Although jQuery is quite powerful, jQuery’s design goal was never to become an animation engine with great performance.

 

• As the codebase of jQuery serves several purposes other than animation, thus layout thrashing is difficult to avoid.
• Memory consumption of jQuery gives rise to garbage collections which in turn are responsible for freezing the animations momentarily
• In the place of RAF or requestAnimationFrame, setInterval is used by jq for protecting novices from them.

 

The stuttering you see when an animation starts is caused by layout thrashing, stuttering when the animation is running is caused by garbage collection and low rate of frames is generally caused if RAF is not present.

 

Examples of Implementation

 

Layout thrashing can be avoided by batching DOM updates and DOM queries together:

 

var currentTop,
currentLeft;

/* With layout thrashing. */
currentTop = element.style.top; /* QUERY */
element.style.top = currentTop + 1; /* UPDATE */

currentLeft = element.style.left; /* QUERY */
element.style.left = currentLeft + 1; /* UPDATE */

/* Without layout thrashing. */
currentTop = element.style.top; /* QUERY */
currentLeft = element.style.left; /* QUERY */

element.style.top = currentTop + 1; /* UPDATE */
element.style.left = currentLeft + 1; /* UPDATE */

 

The browser recalculates computed style data of a page, considering the effects of new updates, when it is forced by queries occurring after the update. Due to this significant overhead is produced for animations which are using small intervals of merely 16ms for running.

 

In the same way, no significant networking is required among existing codebase due to the implementation of RAF. Below we have compared RAF against setInterval in terms of basic implementation.

 

var startingTop = 0;

/* setInterval: Runs every 16ms to achieve 60fps (1000ms/60 ~= 16ms). */
setInterval(function() {
/* Since this ticks 60 times a second, we divide the top property’s increment of 1 unit per 1 second by 60. */
element.style.top = (startingTop += 1/60);
}, 16);

/* requestAnimationFrame: Attempts to run at 60fps based on whether the browser is in an optimal state. */
function tick () {
element.style.top = (startingTop += 1/60);
}

window.requestAnimationFrame(tick);

 

RAF can help to bring a significant improvement in the performance of animation which can be possibly done by making a slight change in the code.

 

CSS Transitions

 

CSS transitions are considered better than jq when it comes to performance as these can offload animation logic directly to the browser and it helps in following ways:

 

• Optimizing memory consumption and DOM interaction for eliminating the problem of stuttering
• Leveraging the RAF principles under the hood
• Forcing acceleration of hardware by leveraging the GPU power for improving the performance of animation

 

However, in reality such optimizations are possible to be done within JavaScript directly and this has been done by GSAP since years. A new engine for animation, Velocity.js, leverages such techniques and along with that offers several other benefits, which will be explored later.

 

Understanding that JavaScript animation can give competition to CSS transitions just gives a glimpse of what lies ahead. The next step is relaxing that in terms of speed JavaScript animations can be much better than transitions.

 

Here we will examine the CSS transitions’ weaknesses:

 

• Forced hardware acceleration of transitions tax GPU and lead to banding and stuttering    in situations of high stress, which get    enhanced on mobile devices. Stuttering   specifically occurs due to overhead which is caused while transferring data from the main   thread of the browser and the compositor thread. A few properties of CSS, such as opacity and transforms, do not get affected by    this overhead.

 

• Any versions pervious than internet explorer 10 does not support transitions, thus leading to the problems of accessibility for        desktop sites, as IE9 and IE8 are quite popular.

 

• JavaScript does not control the transitions, as JavaScript just triggers these, as the browser is unable to optimize transitions in  accordance with JavaScript code which manipulates them.

 

On the other hand, it is possible for animation libraries based on JavaScript to decide if hardware acceleration should be enabled, it is possible for them to work on IE’s every version and they also make a suitable choice for optimizing batched animations.

 

Using raw CSS transitions is recommended while developing exclusively for mobile, as well as when the animations involve only simple state modifications. In such cases, transitions act as native solution, helping you in retaining animation logic within the stylesheets, without letting JavaScript libraries bloat your page. On the contrary, while designing UI which is intricate or an app having stateful UI, ideally you should make use of animation library, to keep the performance of your animations high and easily manage the workflow. Transit is one such library which is considerably helpful when it comes to managing the CSS transitions.

 

JavaScript Animation

 

In terms of performance, JavaScript is definitely on the top, however how much fast it actually is? To begin with, it can be used for building a complex demo in 3D animation which is usually possible with WebGL. Similarly, it can be used for building multimedia teaser, which is generally built using After Effects or Flash. Last, but not the least, it can be used for creating a virtual world, which is commonly built using canvas.

 

Directly comparing the leading libraries of animation, including Transit, in terms of performance, you can visit VelocityjS.org, documentation by Velocity.

 

However a question that arises is how is it possible for JavaScript to reach such high performance levels? Listed below are some optimizations which can be performed by animations based on JavaScript:

 

• DOM Synchronization, tween stack all over the animation cycle to reduce layout thrashing.
• Caching of property values on chained cells for minimizing DOM querying’s occurrence.
• Caching of unit conversion ratios on consecutive element of similar call
• Skipping style up gradation while updates are imperceptible visually

 

Revising the things we have learned regarding layout thrashing, some of the best practices are leveraged by Velocity.js for caching an animation’s end values for running these as upcoming animation’s start values. This way it avoids requerying of DOM for the start values of elements:

 

$element
/* Slide the element down into view. */
.velocity({ opacity: 1, top: “50%” })
/* After a delay of 1000ms, slide the element out of view. */
.velocity({ opacity: 0, top: “-50%” }, { delay: 1000 });

 

In the above written example, it is known by latter Velocity call that it is required to start with 1 as opacity value and 50% as top value, automatically.

 

Performing such optimizations is possible for the browser itself; however this would also mean restricting the ways through which a developed could have crafted the animation code. Similarly, RAF is not used by jQuery, not any optimizations will be imposed by the browsers which might have even the slightest risk of not performing as per expectations or might break the spec.

 

Now let us do a comparison of GSAP and Velocity.js, the two animation libraries of JavaScript with each other.

 

• GASP is an animation platform rich in features, while Velocity is used primarily for making performance in the workflow and animation performance of UI.
• A licensing fee is required for using GSAP by many businesses, whereas Velocity being an open source can be used freely through MIT license.
• Distinguishing Velocity and GSAP is not possible in real projects, performance wise.

 

Ideally GSAP should be used when you need maximum control on timing, such as seek/resume/pause/remapping, motion, such as Bezier curve path or intricate sequencing/grouping. All these features make significance impact on game development, as well as some niche applications, while these are less commonly used in web application UIs.

 

Velocity.js

 

GSAP definitely has better features, but it does not mean that Velocity lacks behind in features. In reality, Velocity is capable of replicating jQuery’s functionality, as well as includes a range of color animations, loops, easings, transforms, scrolling, and class animation.

 

It can be rightly said that Velocity is as good as jQuery, CSS transitions and jQuery UI combined together.

 

Moreover, offering great convenience, the $.queue() method of jQuery is used by Velocity under the hood, allowing it to combine effortlessly with other functions of jQuery, such as $.delay(), $.animate()and $.fade().Not only that, but Velocity’s syntax being similar to $.animate()’s, you need not to change the code of your page.

 

Take a look at the example below which demonstrates how Velocity acts similar to $.animate(), on basic level:

$element
.delay(1000)
/* Use Velocity to animate the element’s top property over a duration of 2000ms. */
.velocity({ top: “50%” }, 2000)
/* Use a standard jQuery method to fade the element out once Velocity is done animating top. */
.fadeOut(1000);

At advanced level, you can use 3D animations for creating intricate scrolling scenes by using just two lines of code:

$element
/* Scroll the browser to the top of this element over a duration of 1000ms. */
.velocity(“scroll”, 1000)
/* Then rotate the element around its Y axis by 360 degrees. */
.velocity({ rotateY: “360deg” }, 1000);

 

 

 

Conclusion
Velocity aims at being the frontrunner when it comes to the convenience and performance of DOM animation. However, it should be remembered that a high performance UI involves more than selecting a good animation library. Optimizing the remaining page is also important.

 

I hope, the above information is helps to  lot.

Thank you…:)

4154 2 Views Today