Which is faster, CSS or JS animation_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:54:50
Original
1254 people have browsed it

Javascript-based animations are secretly as effective as CSS transitions, or even faster. How is this possible? How is this possible when Adobe and Google continue to release media-rich mobile sites that perform as well as native apps?

This article takes a look at DOM animation libraries based on Javascript, such as Velocity.js and GSAP, to see how they are more performant than jQuery and CSS animation effects.

jQuery

Let’s start with the basics: JavaScript and jQuery are mistakenly conflated. JavaScript animations are fast. jQuery slows them down. Why? Because ? Although jQuery is very powerful, it has never been the design goal of jQuery to be a powerful animation engine:

  • jQuery cannot avoid layout bumps, which is due to the animation provided by its code base

  • jQuery's memory consumption often triggers garbage collection, which will freeze the animation from time to time.

  • jQuery uses setInterval instead of requestAnimationFrame (RAF) to protect the new technology from its own effects.

  • It should be noted that layout turbulence is not smooth at the beginning of the animation, and garbage collection is caused by irregularities during the animation. The culprit of smoothness, while not using RAF will result in low frame rates.

    Implementation example

    Avoid DOM query and update combinations that cause layout turbulence:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

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

    A query that occurs after an update will force the browser to recalculate the page's calculated data (while taking the new update effects into account). This will have a significant overhead on the animation, and this is only a tiny 16 millisecond interval. The runtimeout.

    Similarly, implementing RAF does not have to be a significant rework of your existing code base. Let’s compare the basic implementation of RAF to setInterval:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    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 generated Pushing the best possibilities for animation performance, you can make a single change to your code.

    CSS Transformations

    CSS Transformations go beyond jQuery by offloading animation logic to the browser itself. , which is effective in the following aspects: (1) Optimize DOM interaction and memory consumption to avoid lags (bumps), (2) Utilize the RAF principle of the engine, (3) Force hardware acceleration (use the ability of the GPU to improve animation performance).

    However, the reality is that these optimizations can also be performed directly in JavaScript. GSAP has been doing this for many years. Velocity.js, a new animation engine, not only leverages the same technology, but takes it a few steps further - something we'll explore shortly.

    Facing the fact that JavaScript animations can compete with CSS transitions is just the first step in our recovery plan. The second step is to realize that "JavaScript animations can actually be faster than CSS transitions."

    Now let’s talk about the weaknesses of CSS transformations:

  • Forcing hardware acceleration for transition will increase GPU consumption, which will lead to unsmooth operation under high load conditions. This is especially true on mobile devices. (Special cases, such as bottlenecks when data is transferred between the browser's main thread and the formatting thread, can also cause unsmoothness). Certain CSS properties, such as transform and opacity, are not affected by these bottlenecks. Adobe has carefully summarized these issues here.

  • Transition is useless below IE10, causing desktop site usability problems since IE8 and IE9 that are still widespread today.

  • Since transitions are not natively controlled by JavaScript (but simply triggered by JavaScript), the browser has no way of knowing how to optimize them in sync with the JavaScript code that controls these transitions.

  • In contrast, JavaScript-based animation libraries can determine the appropriate hardware to enable. They natively support all versions of IE browsers, and they are especially suitable for batch animation optimization.

    My suggestion is to use native CSS transforms only if you are developing solely for mobile and only implement simple animations. In this environment, transition is a native and efficient solution that allows you to implement all animation logic in the style sheet without adding additional JavaScript libraries, thereby preventing your page from becoming bloated. However, when you are designing a complex UI, or developing an app with UI in different states, you should use an animation library to keep the animation smooth and the workflow easy to manage. Transit is a library that does a particularly good job of managing CSS transformations.

    JavaScript Animation

    Okay, so JavaScript has the upper hand in terms of performance. But how much faster is JavaScript exactly? Okay? Finally? For building a real 3D animation example It is fast enough. Usually you will only see the use of WebGL in the build. And building a small multimedia animation is enough. Usually you will only see the use of Flash or After Effects to build. And building a virtual world is also enough. Typically you'll only see canvas builds.

    For a direct comparison of the leading animation libraries, including Transit (which uses CSS gradient effects) of course, check back to Velocity at VelocityJS.org Documentation on .

    The question remains: How specifically does JavaScript achieve its high level of performance? Here is a short list of optimizations that enable JavaScript-based animations to be performed:

  • Synchronize DOM → Push in the middle of the entire animation chain to minimize layout jitter.

  • Cache property values ​​for the entire chain of calls to minimize DOM lookups (these are Pitfalls of high-performance DOM animation).

  • Cache the unit conversion rate of the entire same-level element in the same call (such as px to %, em, etc.).

  • Skip style updates when updates might not be visually visible.

  • Recall what we learned earlier about layout thrashing, which Velocity.js leverages These best practices to cache the animation end value for reuse as the start value for subsequent animations, thus avoiding having to re-query the DOM to get the element's start value:

    1

    2

    3

    4

    5

    $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 example above, the second Velocity call knows that it should automatically start with an opacity of 1 and a top of 50%.

    Browsers themselves will eventually be able to perform many of these same optimizations, but doing so will significantly reduce the number of ways developers can craft animation code. So, by the same token, since jQuery doesn't use RAF (as mentioned above), browsers don't force it to optimize it, giving even a small chance of breaking specs or deviating from expected behavior.

    Finally, let’s compare the two JavaScript animation libraries (Velocity.js and GSAP) with each other.

     GSAP was the first animation library to demonstrate JavaScript's impressive DOM animation performance. It does, however, have a few drawbacks:

  • In medium-to-high stress animations, GSAP's DOM interaction overhead causes dropped frames at the start of, and between, animations.

  • Whereas Velocity.js is released under the ultra-permissive MIT license, GSAP is closed-source and requires an annual licensing fee for many types of businesses.

  • Because GSAP is a full animation suite, it is triple the size of Velocity. However, since GSAP is so richly-featured, it does have the benefit of being a Swiss Army Knife of animation.

  •  My recommendation is to use GSAP when you require precise control over timing (e.g. remapping, pause/resume) and motion (e.g. bezier curve paths). These features are crucial for game development and certain niche applications, but are typically not needed in web app UI's. Lightweight. On the contrary, in only 7kb after compression, Velocity not only replicates all the functions of jQuery $.animate(), it also adds color animation, transformations, loops, easing effects, class animations and scrolling. Packaged in.

    In short, Velocity is the best combination of jQuery, jQuery UI, and CSS gradient effects.

    In addition, from a convenience point of view, Velocity is in the hood (cover, roughly meaning Using jQuery's $.queue() method under a public interface), you can achieve seamless interoperability with jQuery's $.animate(), $.fade(), and $.delay() functions. And , since the syntax of Velocity is the same as the syntax of $.animate(), you don’t need to change any code on the page.

    Let’s take a quick look at Velocity.js. At a basic level, Velocity Behaves the same as $.animate():

    1

    2

    3

    4

    5

    6

    $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 its most advanced level, it is possible to create complex scrolling scenes with 3D animation? Almost as long as Two simple lines of code:

    1

    2

    3

    4

    5

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

    End

    Velocity’s goal is to remain the leader in animation performance and convenience in the DOM. This article focuses on the former. Head on over to VelocityJS.org to learn more about the latter.

    Before we conclude, remember that a high-performance UI isn’t just about choosing more libs. The rest of your page should be optimized as well. You can learn more and more dreamy content from Google talks:

  • Jank Free

  • Rendering Without Lumps

  • Faster Websites

  • Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template