CSS VS JS Animation, which is faster [translate]

Source: Internet
Author: User
Tags comparable setinterval

English Original: Https://davidwalsh.name/css-js-animation

The original author Julian Shapiro is the author of Velocity.js, Velocity.js is an efficient and easy-to-use JS animation library. In the "JavaScript Web page animation design" In the book of this library has a lot of more specific analysis of velocity and JS animation is interested in a look.

How can JavaScript-based 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 a little bit about 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 don't confuse each other wrong. Javascript animations are fast, and jQuery animations slow down. Why is it? Because although JQuery is very powerful, its design goal is not an efficient animation engine:

1.JQuery cannot avoid layout thrashing, as it is not just about serving animations, but also for other scenarios.

2.JQuery of memory consumption often triggers a garbage collection mechanism, and garbage collection can temporarily get the animation stuck.

3.JQuery uses setinterval instead of Requestanimationframe (RAF), in order to avoid the RAF in the loss of focus when the animation (translator Note: JQuery3.0 integrated RAF, IE8 and the following versions are not supported).

Note that layout thrashing is the reason for the animation to stutter at the beginning, garbage collection is the cause of the lag in the animation process, and not using the RAF usually results in a low animation frame rate.

Implementation examples

Avoid layout thrashing, which consists of bulk sync operation DOM requests and DOM updates.

varcurrenttop, 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*/

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 is not much of a performance penalty under normal operation, but it can lead to significant performance overhead in animations that are 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 force you to refactor the current code a lot. Let's compare the difference between using the RAF and using setinterval:

varStartingtop = 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.*/Element.style.top= (Startingtop + = 1/60);}, 16);/*requestanimationframe:attempts to run at 60fps based on whether the browser are in a optimal state.*/functiontick () {Element.style.top= (Startingtop + = 1/60);}window.requestanimationframe (tick);

The RAF can provide the greatest possible boost to animation performance, and for that you just need to make a simple modification to your code.

CSS transitions

CSS transition can perform better than jQuery animations, transition the animation logic to the browser itself. Its advantages are reflected in:

1. Avoid stalling by optimizing DOM operations and memory consumption

2. Using the RAF's underlying principles

3. Force hardware acceleration (using GPU acceleration to improve animation effects).

However, JavaScript can actually use these optimizations directly. GSAP has been doing these optimizations for some years now. Velocity.js, a new animation engine, not only implements the same technology, but also goes farther. We'll talk about that later.

In the face of reality, allowing Javascript animations to compete with CSS animation performance is just the first step in our recovery plan. The second step is to realize the fact that Javascript animations are faster than CSS animations!

Let's start by testing the flaws in CSS animations:

The 1.Transition force uses GPU acceleration, which causes the animation to stutter and bind under high load. This situation is exacerbated on mobile devices. (It is particularly necessary to note that the lag is caused by overloading when the data is transferred between the main thread of the browser and its sorting threads.) Some CSS properties, such as transforms and opacity, are not subject to this limitation. The Adobe Brothers blog has talked about this topic.

2.Transition does not work in IE10, which causes compatibility problems in the IE8 and IE9 of many desktop scenarios.

3. Since transition cannot be natively controlled by JavaScript (just triggered by JavaScript), the browser does not know how to optimize the operation of transition's JavaScript code.

Conversely, JavaScript-based animation libraries can decide when to enable hardware acceleration, and they are naturally working in the versions of IE, and they are ideal for batch animation optimization.

My advice is to use native CSS transitions on pages developed specifically for mobile, and your animations consist only of simple state changes. In this case, transitions is a high-performance inline method that allows you to keep all the logic of the animation in a CSS stylesheet without the use of too many JavaScript libraries resulting in page bloat. However, if you are designing a complex UI animation or are developing a multi-state UI app, remember to use the animation library so that your animations are in high-performance state and your workflow is in a manageable state.

JavaScript animations

Well, JavaScript has the advantage of being able to use it. But how fast can JavaScript be? Start-fast enough to create a contrasting 3D presentation animation, as you would expect, usually done with WebGL. Fast enough to build a complex multimedia animation, usually using flash or after effects.

It's almost ready to build a virtual world that you can usually do with canvas.

To directly compare the performance of the mainstream animation library, including transit (which uses CSS transition), you can take a look at Velocity's official documentation here: velocityjs.org

The previous question was: How does JavaScript achieve high performance?

Below is a list of some optimizations that JavaScript's animation library can perform:

1. Sync dom-"Adjusts the animation chain between stacks to minimize the layout jitter.

2. Cache attribute values in chained calls to minimize the occurrence of DOM queries (this is the Achilles heel of high-performance animations).

3. When the update is basically not visible, skip the style update.

You can revisit the layout jitter we discussed earlier, and velocity.js use these best practices to cache the animation end value so that it is reused as the starting value for the subsequent animation. This avoids querying the starting value of the DOM element again.

     $element    /**    /1, Top: "50%"})/*       */    0, Top: " -50%"}, {delay:1000});

In the example above, the second velocity call is known to start automatically when opacity is 1,top to 50%.

Browsers can perform optimizations like this on their own, but doing so will largely limit the way developers manually write animated code.

Therefore, for the same reason, jquery does not use the RAF (see above), and the browser never implements optimizations that might break the spec or deviate from the expected behavior.

Finally, let's compare the two JavaScript animation libraries (velocity and GSAP).

1.GSAP is a fast and feature-rich animation library platform. Velocity is a lightweight tool that greatly improves UI animation performance and working with Liu.

2.GSAP is paid for a wide variety of commercial applications, velocity is fully open source free, and it uses a very free mitlicence.

3. In practical applications, the performance of the two is comparable.

My advice is that you need precise control over time using GSAP (for example: remapping, pause \ Continue \ Skip), move (such as Bezier), or complex animation combination \ queue. These features are important for game development and some special applications, but are less common in Web applications.

Velocity.js

GSAP has a rich feature, but does not mean that velocity is not rich in its function. In contrast, in the 7KB package after compression, velocity not only realizes all the functions of jqueryanimate, but also packs color animations, transformations, loops, moves, animations, and scrolling.

In short, velocity is the best combination of jquery, jquery UI, and CSS transitions.

Further, from a convenient point of view, V uses the jquery $.quene () method at the bottom. So and jquery's $.animate (), $.fade (), and $.delay () are seamlessly interoperable. In addition, because the syntax of V and $.animate () are exactly the same, the Code of the page does not need to be changed.

Let's take a quick look at v. V and animate have exactly the same syntax:

$element    . Delay (+/*/        "50%"}, +)     /*  * *    . FadeOut (1000);

Advanced usage inside, complex scrolling scenes with 3D animations can be created-only 2 lines of simple code:

$element     /*  *    /. Velocity (    "Scroll",+/** /      "360deg"}, 1000);

Summarize

The goal of V is to become a leader in the performance and convenience of Dom animations. The focus of this article is the former. The velocityjs.org mentioned above can understand the latter.

Before we end, keep in mind that a high-performance UI is more than just choosing the right animation library. The rest of the page should also be optimized.

CSS VS JS Animation, which is faster [translate]

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.