CSS vs JS Animation: Who is faster?

Source: Internet
Author: User
Tags comparable
This article translates from the Julian Shapiro CSS vs. JS Animation:which is Faster?. Julian Shapiro is also the creator of Velocity.js. This is a very efficient, easy-to-use JS animation library. He has a high attainments in web animation.

How can Javascript animations always be as fast or even faster as CSS transition? What secret is it? How did Adobe and Google make their rich media mobile sites comparable to the native app?

This article will tell you step-by-step why Javascript-based DOM animation libraries, such as Velocity.js and GSAP, can be more efficient than jQuery and CSS-based animation libraries.

Jquery

Let's start with the basics: Javascript and jQuery can't be confused. Javascript animations are fast, and jQuery animations are slow. Why is it? Because although JQuery is exceptionally powerful, its design goals are not an efficient animation engine:

    • JQuery cannot avoid layout thrashing (someone likes to translate it into "layout bumps", which can lead to extra relayout/reflow), because its code is not just for animations, it is also used in many other scenarios.

    • jquery's memory consumption is large and often triggers garbage collection. While garbage collection triggers, it's easy to get the animation stuck.

    • jquery uses setinterval instead of Reqeustanimationframe (RAF) because the RAF stops triggering when the window loses focus, which results in jquery bugs. (The RAF is now used by jquery)

Note that the layout thrashing will cause the animation to stutter at the beginning, and the garbage collection trigger will cause the animation to stutter while not using the RAF, resulting in a low animation frame rate.

Implementation examples

To avoid layout thrashing, we need to bulk access and update the DOM.

var currenttop,    currentleft;/* has layout thrashing. */currenttop = element.style.top;/* Access */element.style.top = Curre Nttop + 1; /* Update */currentleft = Element.style.left; /* Access */element.style.left = currentleft + 1; /* Update *//* no layout thrashing. */currenttop = Element.style.top; /* Access */currentleft = Element.style.left; /* Access */element.style.top = currenttop + 1; /* Update */element.style.left = currentleft + 1; /* UPDATE */

An access operation after an update operation forces the browser to recalculate the style of the page element (because the updated style is applied to get the correct value). This does not have much of a performance penalty under normal operation, but it can lead to significant performance overhead when placed in an animation that is only 16ms apart. The performance of the animation can be greatly improved by simply altering the order of operations.

Similarly, using the RAF will not allow you to refactor the code in large numbers. Let's compare the difference between using the RAF and using setinterval:

var startingtop = 0;/* Setinterval:runs every 16ms to achieve 60fps (1000MS/60 ~= 16ms).  */setinterval (function () {/    * Since This ticks a second, we divide the top property ' s increment of 1 unit per 1 second by 60. *    /Element.style.top = (startingtop + = 1/60); */* requestanimationframe:attempts to run at 60fps based on Whethe R The browser is a optimal state. */function tick () {    Element.style.top = (startingtop + = 1/60);} Window.requestanimationframe (tick);

You only need to modify the code slightly to use the RAF, you can make your animation performance greatly improved.

CSS Transition

The animated logic of CSS transition is performed by the browser, so it performs better than jQuery animations. Its advantages are reflected in:

    • Reduce lag by optimizing DOM operations and avoiding memory consumption

    • Using a mechanism similar to the RAF

Forcing hardware acceleration (with GPU to improve animation performance)

However, JavaScript can actually use these optimizations as well. GSAP has been doing these optimizations for a long time. Velocity.js is an emerging animation engine that not only makes these optimizations, but even goes farther. We'll talk about that later.

In the face of reality, making Javascript animations comparable to the performance of CSS animations is just the first step in our great plan. The second step is the play, to make Javascript animation faster than the CSS animation!

Let's take a look at the flaws of the CSS animation library:

    • The Transition enforces hardware acceleration for GPU use. Causes the browser to always be in a state of high-load operation, which will cause the animation to become stuttering. This is more serious on mobile browsers. (in particular, it is easy to lead to the performance of the data when it is transmitted frequently between the main thread of the browser and the synthetic threads.) Some CSS properties are not affected. Adobe's blog has talked about this issue.

    • Browsers under IE 10 do not support transition. At present, IE8 and IE9 are still very popular.

    • Transition cannot be completely controlled by JavaScript (only by JavaScript to trigger transition), because the browser does not know how to let JavaScript control the animation while simultaneously optimizing the performance of the animation.

    • In turn, Javascript can determine when hardware acceleration is enabled, it can support a full version of IE, and it can be optimized for batch animation.

My advice is: when you only develop on the mobile platform, and the animation is only a simple state switch, it is appropriate to use a pure CSS transition. In this case, the transition is a high-performance native support scenario. It allows you to put the animation logic inside the style file without flooding your page with Javascript libraries. However, if you are designing a complex rich client interface or developing an app with a complex UI state. Then I recommend you use an animation library so that your animations stay productive and your workflow is more manageable. There is a special library to do the very good, it can use Javascript control CSS transition. This is Transit.

Javascript Animations

So Javascript can perform better than CSS transition. But how many pieces does it have? It's fast enough to build a demo of a 3D animation, and it usually needs WebGL to do it. And it's fast enough to build a small multimedia animation that usually requires Flash or after Effects to complete. And it's fast enough to build a virtual world that usually requires canvas to complete.

To more directly compare the performance of the mainstream animation library, including Transit (using CSS transition), let's open the velocity's official documentation.

The previous question was: How does Javascript achieve high performance? Here's a list of things that Javascript-based animation libraries can do:

    • Synchronize Dom--fine-tune the stack throughout the animation chain to achieve the smallest layout thrashing.

    • Cache the attribute values in chained operations, which minimizes the query operation of the DOM (this is the Achilles heel of the high-performance Dom animation)

    • Caches the unit conversion ratio (for example, px to%, EM, and so on) in a call to the same cross-layer element

    • Ignoring DOM updates that are too small to be seen at all

Let's review what we learned earlier about layout thrashing's knowledge points. Velocity.js uses these best practices to cache the property values at the end of the animation, which is used immediately after the next animation begins. This avoids re-querying the starting property value of the animation.

$element/    * Slide the element down into view. *    /. Velocity ({opacity:1, Top: "50%"})/    * After a delay of 100 0MS, slide the element out of view. *    /. Velocity ({opacity:0, Top: " -50%"}, {delay:1000});

In the example above, the second call to Velocity has been known that the value of opacity starting at 1,top is 50%.

Browsers can also use optimizations similar to this, but to do these things too aggressively, the use of the scene will be limited, developers will probably write the bug of the animation code. For this reason jquery does not use the RAF (as mentioned above), and the browser never enforces optimizations that might break the norm or might deviate from the desired behavior.

Finally, let's compare the next two JavaScript frameworks (Velocity.js and GSAP).

    • GASP is a fast and feature-rich animation platform. Velocity is more lightweight, and it greatly improves UI animation performance and workflow.

    • GSAP require a fee to be used for commercial products. Velocity is completely free and uses an extremely high degree of freedom in the MIT protocol.

    • In terms of performance, they are almost equal and difficult to distinguish between winners and losers.

I personally recommend using GSAP when you need the following features: precise control of time (e.g. remapping, pause/Resume/skip), or the need for action (e.g. Bezier path), or complex animation combinations/queues. These features are important for game development or complex applications, but not for the normal web App UI.

Velocity.js

The previous mention of GSAP is rich in functionality, but this does not mean that Velocity has a simple function. In contrast, Velocity is only 7kb after zip compression, which not only implements all the functions of the JQuery animate method, but also includes features such as colors, transforms, loops, Easings, class animations, and scrolling animations.

In a nutshell, Velocity includes the functionality of jquery, jquery UI, and CSS transition.

Further from a usability perspective, Velocity uses the $.queue () method of jquery, so it can seamlessly transition to the $.animate (), $.fade (), and $.delay () methods of jquery. And Velocity's syntax is the same as $.animate (), so we don't need to modify the existing code on the page at all.

Let's take a quick look at the velocity.js example:

$element    . Delay (+)/* Use Velocity to animate the element's top property over    a duration of 2000ms. */    . vel Ocity ({top: "50%"}, +)/    * Use a standard JQuery method to fade the element out once Velocity was done animating to P. *    /. FadeOut (1000);

The following is an advanced usage: Scrolls the page to the current element and rotates the element. Such animations require only a few simple lines of code:

$element    /* Scroll the browser to the top of this element over a duration of 1000ms. * *    . Velocity ("Scroll", 1000) c7/>/* then rotate the element around its Y axis by degrees. *    /. Velocity ({rotatey: "360deg"}, 1000);

Summarize

Velocity's goal is to become the most user-friendly library in the DOM animation field. This article focuses on the performance aspect. Ease of use can go to velocityjs.org to understand.

Before you finish, remember that a high-performance UI is more than just choosing the right animation library. Other code on the page also needs to be optimized. Take a look at some of Google's great speeches:

Jank Free

Rendering without lumps

Faster Websites

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.