Comparison of CSS animation vsJavaScript Animation

Source: Internet
Author: User
JavaScript animation makes up for these two shortcomings. It has strong control capabilities and can control and transform a single frame. At the same time, it is well-written and completely compatible with IE6 and has powerful functions. However, considering that the transform matrix of CSS animation is C ++-level computing, it must be faster than javascript-level computing. The dependency on libraries is also a headache. Advantages of CSS3 Animation:

  • The performance is slightly better, And the browser will optimize the CSS 3 animation (for example, creating a new layer to run the animation)

  • Relatively simple code

But its disadvantages are also obvious:

  • Not flexible enough in animation control

  • Poor compatibility

Some animation functions cannot be implemented (such as scrolling and parallax scrolling)

JavaScript animation makes up for these two shortcomings. It has strong control capabilities and can control and transform a single frame. At the same time, it is well-written and completely compatible with IE6 and has powerful functions. However, considering that the transform matrix of CSS animation is C ++-level computing, it must be faster than javascript-level computing. The dependency on libraries is also a headache.

Javascript is more reliable for some animations with complex control. When implementing some small interaction effects, we should consider CSS more.

In terms of actual project experience, the efficiency of the two schemes for animation is not much different in the same context, and the efficiency is even more affected:

  • Whether to cause layout

  • Repaint Area

  • Whether there are high-consumption attributes (css shadow, etc)

  • Enable hardware acceleration?

Dynamically changing the margin and height of regular stream elements will lead to a large layout process, which is as slow as JS or CSS3.
The translate3D of the dynamic element naturally enables 3D acceleration. There is no significant difference in frame rate between setTimeout/setInterval/requestAnimationFrame and CSS3.

The main difference today is that

1. Functional coverage. JS is larger than CSS3

  • @ Keyframes for defining an animation process does not support recursive definition. If there are multiple similar animation processes that need to be generated by adjusting multiple parameters, there will be a lot of redundancy (such as jQuery Mobile's animation solution), while JS can naturally implement multiple different animation processes with a set of functions.

  • In terms of time scale, the @ keyframes animation granularity is coarse, while the JS animation granularity control can be very fine

  • CSS3 animations support very few and not flexible enough time functions.

  • With existing interfaces, CSS3 animation cannot support more than two State transformations.

2. Implementation/refactoring is difficult. CSS3 is simpler than JS, and performance tuning is fixed.

3. For low-version browsers with poor frame speed, CSS3 can be naturally downgraded, while JS requires additional code.

4. CSS3 has compatibility problems, while JS does not have compatibility problems most of the time.


The following shows how Javascript-based DOM animation libraries (such as Velocity. js and GSAP) are more efficient than jQuery and CSS-based animation libraries.

JQuery

Let's start from the basics: Javascript and jQuery cannot be confused. Javascript animations are fast, while jQuery animations are slow. Why? Although jQuery is exceptionally powerful, its design goal is not an efficient animation engine:

  • JQuery cannot avoid layout thrashing (some people like to translate it into "layout bumps", leading to excessive relayout/reflow) because its code is not only used for animation, but also used in many other scenarios.

  • JQuery consumes a lot of memory and often triggers garbage collection. However, animation can easily be stuck when garbage collection is triggered.

  • JQuery uses setInterval instead of reqeustAnimationFrame (RAF), because RAF stops triggering when the window loses focus, which leads to jQuery bugs. (Now jQuery has used RAF)

Note that layout thrashing will cause the animation to get stuck at the beginning, and the garbage collection trigger will cause the animation to get stuck during running. If RAF is not used, the animation frame rate will be low.

Implementation example

To avoid layout thrashing, We need to access and update the DOM in batches.

Var currentTop, currentLeft;/* has layout thrashing. */currentTop = element. style. top;/* access */element. style. top = currentTop + 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 */

After the update operation, the access operation forces the browser to recalculate the style of the page element (because the updated style must be applied to obtain the correct value ). This does not cause much performance loss in general operations, but placing an animation at an interval of only 16 Ms will lead to significant performance overhead. You only need to slightly change the operation sequence to greatly improve the animation performance.

Similarly, using RAF won't allow you to refactor a lot of code. Let's compare the difference between RAF and setInterval:

var startingTop = 0;/* setInterval: Runs every 16ms to achieve 60fps (1000ms/60 ~= 16ms). */setInterval(function() {    /* Since this ticks 60 times a second, we pide 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);

You only need to slightly modify the code to use RAF, which can greatly improve your animation performance.

CSS Transition

The CSS transition animation logic is executed by the browser, so its performance can be better than jQuery animation. Its advantages are as follows:

  1. Optimize DOM operations to avoid memory consumption and reduce lag.

  2. Use a mechanism similar to RAF

  3. Force hardware acceleration (improves animation performance through GPU)

However, Javascript can also use these optimizations. GSAP has been doing these optimizations for a long time. Velocity. js is an emerging animation engine. It not only performs these optimizations, but even goes further. We will talk about this later.

In the face of the facts, making Javascript animation comparable to CSS animation's performance is only the first step of our great plan. The second step is the most important thing, making Javascript animation faster than CSS animation!

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

  1. Transition enforces GPU hardware acceleration. As a result, the browser is always running at a high load, which will make the animation slow. This is more serious in Mobile browsers. (It should be noted that when data is frequently transmitted between the main thread of the browser and the merging thread, performance is especially consumed, which may lead to choppy. Some CSS attributes are not affected. Adobe's blog talked about this issue.

  2. Browsers with less than IE 10 do not support transition. At present, IE8 and IE9 are still very popular.

  3. Transition cannot be completely controlled by Javascript (it can only be triggered by Javascript), because the browser does not know how to allow Javascript to control the animation and optimize the animation performance at the same time.

On the other hand, based on Javascript, you can decide when to enable hardware acceleration. It supports the full version of IE and can fully optimize batch animation.

Javascript Animation

Therefore, Javascript can have better performance than CSS transition. But how many blocks does it have? It is almost enough to build a 3D animation demo, which usually needs to be completed using WebGL. And it is almost enough to build a small Multimedia Animation, which usually requires Flash or After Effects. In addition, it is almost possible to build a virtual world, which usually requires canvas.

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

The previous question is: how does Javascript achieve high performance? The following is a list of what Javascript-based animation libraries can do:

  1. Synchronize DOM-> fine-tune the stack in the entire animation chain to achieve the smallest layout thrashing.

  2. Cached attribute values in chained operations to minimize DOM query operations (this is the Achilles' heel of high-performance DOM animation)

  3. Cache unit conversion rate (for example, px converted to %, em, and so on) in a single cross-Layer Element call)

  4. Ignore DOM updates that are not visible at all.

Let's review the previous knowledge points about layout thrashing. Velocity. js uses these best practices to cache the attribute values at the animation end and use them at the next animation start. This avoids re-querying the starting attribute value of an animation.

$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 preceding example, when Velocity is called for the second time, the initial opacity value is 1 and the top value is 50%.

Browsers can also use similar optimizations, but these operations are too radical and use cases are restricted. Developers may write animated code with bugs. JQuery does not use RAF (as mentioned above) for this reason, and the browser will never forcibly implement optimization that may break the specifications or possibly deviate from the expected behavior.

Finally, let's compare two Javascript frameworks (velocity. js and GSAP ).

  • GASP is a fast and functional animation platform. Velocity is more lightweight, which greatly improves the UI animation performance and workflow.

  • GSAP must be paid for commercial products. Velocity is completely free, and uses the MIT protocol with extremely high degrees of freedom.

  • In terms of performance, the two are almost identical, and it is difficult to distinguish between them.

Velocity. js

GSAP has a wide range of features, but this does not mean that Velocity is simple. On the contrary, Velocity only has 7 kb After zip compression. It not only implements all functions of the jQuery animate method, it also includes color, transforms, loop, easings, class animation, and scroll animation.

In short, Velocity includes jQuery, jQuery UI, and CSS transition functions.

In terms of usability, Velocity uses jQuery's $. the queue () method, so you can seamlessly transition to jQuery's $. animate (), $. fade () and $. delay () method. The syntax of Velocity is the same as that of $. animate (), so we do not need to modify the existing Code of the page.

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

$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);

The following is an advanced usage: Scroll the webpage to the current element and rotate the element. Such an animation requires 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)    /* Then rotate the element around its Y axis by 360 degrees. */    .velocity({ rotateY: "360deg" }, 1000);

Velocity aims to become the best library for DOM animation with the highest ease of use performance. This article focuses on performance. For ease of use, go to VelocityJS.org.

Remember that a high-performance UI is not just a proper animation library. Other code on the page also needs to be optimized.

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.