Delve into some of the ways to make JavaScript animations fluent _javascript tips

Source: Internet
Author: User
Tags garbage collection setinterval

JavaScript based animation is the same as the CSS transition effect, or even faster, how can this be? And how is it possible that Adobe and Google continue to publish rich-media mobile sites that are comparable in performance to local applications?

This article looks at JavaScript-based Dom animation libraries, such as Velocity.js and GSAP, to see how they can be more performance-efficient than jquery and CSS animations.
JQuery

Let's start with the basics: JavaScript and jQuery are confused by mistake. JavaScript animations are quick. JQuery slowed it down. Why? Because-even though jquery is very powerful-becoming a powerful animation engine is never a jquery design goal:

    • JQuery cannot avoid a bumpy layout because its code base provides a variety of uses beyond animations.
    • The memory consumption of jQuery often triggers garbage collection, which lets the animation freeze down from time to time.
    • JQuery uses setinterval rather than requestanimationframe (RAF) to protect the new technology from its own impact.

It should be noted that the layout bumps in the beginning of the animation is not smooth, garbage collection is caused by the animation period is not smooth culprit, and not using RAF will lead to low frame rate.

implementation example

Avoid the combination of DOM queries and updates that cause a bumpy layout:

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 = El Ement.style.top; /* Query *
/Currentleft = element.style.left/* Query/
 
element.style.top = currenttop + 1; * UPDATE/
E Lement.style.left = Currentleft + 1; * UPDATE * *

The query that occurs after the update forces the browser to recalculate the calculated data for the page (while taking into account the new update effect). This creates a significant overhead for the animation, which is just a 16 millisecond interval run timeout.

Similarly, implementing RAF does not have to be a significant rework of your existing code base. Let's take RAF's foundation and compare it with setinterval:

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

RAF produces the greatest possibility of driving animation performance, and you can make a single change to your code.

CSS transformations

CSS transformations are beyond jquery by throwing animation logic into the browser itself, which is effective in the following ways: (1) Optimizing DOM interaction and memory consumption to avoid cotton (bumps), (2) using the RAF principle of the engine, (3) Force hardware acceleration (leveraging GPU capabilities to improve animation performance).

The reality, however, is that these optimizations can also be executed directly in JavaScript. GSAP has been doing this for years. Velocity.js, a new animation engine, not only uses the same technology, but also goes a little further-we'll be exploring that soon.

To face the fact that JavaScript animations can be converted to CSS competition is just the first step in our recovery program. The second step is to implement "JavaScript animations can actually be converted faster than CSS."


Now we're going to start talking about the weaknesses of CSS transformations:

    • Transition forcing hardware acceleration will increase GPU consumption, resulting in high load situations that will not run smoothly. This is especially true on mobile devices. (in exceptional cases, such as when data is passed between the main browser thread and the layout thread), the bottleneck is also not fluent. Some CSS properties, such as transform and opacity, are not affected by these bottlenecks. Adobe has carefully summed up these issues here.
    • Transition is not used below IE10, resulting in the availability of desktop sites since IE8 and IE9 are still widespread.
    • Since transition is not controlled by JavaScript primitives (but only by JavaScript), browsers cannot learn how to optimize them synchronously with JavaScript code that controls these transition.

On the contrary, JavaScript based animation libraries can determine the right hardware to turn on themselves. They natively support various versions of IE browsers, and they are especially suited for batch animation optimization.

My advice is to use native CSS transformations only if you are developing the mobile side alone and implementing simple animations only. In this environment, transition is a native, effective solution that allows you to implement all the animation logic in your stylesheet without adding additional JavaScript libraries to prevent your pages from becoming bloated. However, when you are designing a complex UI, or developing an app that has a different state of the UI, you should use an animation library to keep the animation fluent while making the workflow manageable. Transit is a library that is especially good at managing CSS transformations.

JavaScript Animation

Well, that JavaScript has the upper hand in terms of performance. But how fast is JavaScript exactly? Well--initially--for building a real 3D animation example is fast enough, usually you'll only see the use of WebGL in the build. and building a small multimedia animation is enough, usually you see only use flash or after effects build. And it's enough to build a virtual world, and usually you'll only see Using canvas constructs.

For the leading animation library, and of course include transit (which uses a CSS gradient effect), make a direct comparison and look back at the velocity on the velocityjs.org document.

The question remains: how does JavaScript specifically achieve its high level of performance? The following is a short list of optimizations that can be performed on JavaScript based animations:

    • Sync dom→ The entire animation chain in the middle of the stack to minimize the layout jitter.
    • Cache property values for the entire chained call to minimize the occurrence of DOM queries (these are the pits for high-performance Dom animations).
    • The unit conversion rate of the entire same level element is cached in the same call (px to%, EM, etc.).
    • Skips the style update when the update may not be visually visible.


Looking back at our previous knowledge of layout bumps, Velocity.js used these best practices to cache the animation end values for reuse as the starting values for subsequent animations, thereby avoiding requery of the DOM to get the element's start value:

$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 Velocity call knows that it should start automatically from opacity 1 and top to 50%.

The browser itself can ultimately perform many of these same optimizations, but doing so can significantly reduce the way that the developer can make animated code. Therefore, for the same reason that jquery does not use RAF (as described above), the browser will not force it to optimize it, or even give a small chance to break the specification or deviate from the expected behavior.

Finally, we compared the two JavaScript animation libraries (Velocity.js and GSAP) to each other.


GSAP is the first animated library to use in the demo JavaScript DOM impressive animation performance. It does, but there are some drawbacks:

    • In medium to high load animations, the GSAP DOM interaction overhead causes the animation to lose frames at the beginning and in the process.
    • Instead, Velocity.js is released under the ultra Loose MIT license, GSAP is closed source and requires licensing annual fees for many business classes.
    • Because GSAP is a complete animation suite, it is three times times the Velocity size. However, GSAP has such a rich function to help it become animated by the Swiss Army Knife.

I recommend that you use GSAP when you need precise control over timing (such as redrawing, pausing/resuming) and motion (such as Bezier curve paths). These features are critical in game development and in some special applications, but are not typically used in Web page application UI.

Velocity.js

The rich nature of quoting GSAP does not mean that velocity itself is lightweight in character. Instead, in the only 7kb compressed, velocity not only replicates all the features of the jquery $.animate (), it also packs color animations, transformations, loops, easing effects, animation, and scrolling.

In short, velocity is the best combination of the Jquery,jquery UI and the CSS gradient effect.

Furthermore, from a convenient point of view, Velocity uses the $.queue () method of jquery under the hood (lid, presumably the public interface) so that the $.animate (), $.fade (), and $.delay () of jquery can be implemented. Seamless interoperability of functions. And since Velocity's syntax is the same as that of $.animate (), you don't need to change any of the code on the page.

Let's take a quick look at the velocity.js. At the base level, velocity behaves the same as $.animate ():

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

At its highest level, you can create a complex scrolling scene with 3D animations-almost as long as two simple lines of code are used:

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

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.