Did you know?

Tween is a term used by animators and software engineers to define the numeric start, end and the inbetween values used in digital animation, while the digital animation uses these tween values on a given frequency (interval) or scaled by hardware capability (monitors refresh rate, GPU vertical sync, etc). The term was introduced to the world of web development by early Javascrpt libraries and later used in dedicated animation libraries such as GSAP, Dynamics, Velocity, Shifty, our own KUTE.js here and many others. When used as a verb, it actually reffers to the interpolation of the values.

Tween Object is a Javascript Object that stores temporarily or for a given time a set of variables such as tween values, HTML elements to animate, CSS properties and other tween options to be used for animation. To improve performance on repetitive animations, this object can be cached and reused whenever needed. In Javascript animation, the term tween actually refers to the tween object.

polyfill is a term introduced by Remy Sharp back in 2009 as "a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively". Basically a polyfill covers what legacy browsers don't support or in other cases corrects the implemented behavior that is different from the standards. More details.

requestAnimationFrame is a Javascript method developed to enable hardware acceleration animations for the web today. In Javascript, the window.requestAnimationFrame(callback); method is all we need to setup animations really for all the above mentioned animation engines. Some developers built a polyfil to cover the legacy browsers chaos.

JANK is a term used when browsers miss frames due to long script execution and/or long layout recomposition. JANK is the phenomenon reffering to severe frame drops. Luckily there are people who explain all about it, so you don't have to stay in the dark.

Methods are functions that create tween objects or control the animation for KUTE.js, so we will encounter mostly main methods and tween control methods. Once a main method is used, then the control methods apply in a specific order.

How Does It Work?

Well, first things first: it's smart built. Let's briefly explain the phases:

  1. On first initialization KUTE.js creates some variables such as supported properties and their default values, the user's browser prefix, the true scroll container (some browsers actually scroll the body, while others prefer the HTML tag), a boolean variable that makes KUTE.js aware it's working with IE8, as well as other variables required during the main thread. This phase is very important for the performance on the next phases.
  2. In the next phase it's going to build the tween object with the chosen method according to it's distinct functionalities. If the chosen method is .to() KUTE.js will look for the current values of the properties used or assign the default values built in the previous phase. For both methods, KUTE.js collects all the data, processes values and options (for instance easing functions need to be processed if you use a string like 'easingElasticOut', right?) and builds the tween object, with all properties' values start and values end, measurement units, tween options and callback functions.
  3. In the third phase KUTE.js is ready to start the animation, but the animation starts only after the .start() function, if used, has finished. When animation starts, KUTE.js will start ticking on the frequency decided by requestAnimationFrame or setInterval for legacy browsers, quickly updating the style for the properties and execute the update:function callback if any. Also while animating, KUTE.js will begin listening for your tween control input such as .pause() or .stop() or any other. Also, when a certain tween control method is used, KUTE.js will execute it's specific callback, if used.
  4. When tween animation is finished, the complete:function callback function is executed and then KUTE.js starts the animation for any chained tween, or else will stop ticking with cancelAnimationFrame to save power.

Basically, this is it!

A Note On Performance

As said before, performance varies from case to case; this chapter aims to explain what you should expect working with animation engines in these various scenarios at maximum stress, usually when your CPU cooler starts to work really hard, and how scalable performance can really be on various machines, operating systems or mobile devices. We'll dig into each case, by property type or anything that can be considered a factor of influence.

Function Nesting

This could be one of the most important factors that influence performance, because we neglect this fact most of the time and changing the scope of an animation engine is important to look after. A quick example would be when we create tween objects on events such as click, scroll or resize, we basically set a totally different scope for the animation and we fill the memory with large chunks of trash/jank, especially on events like resize.

A better way to handle this is to create the tween objects outside the event handlers and only start the animation with these handlers when certain conditions are met. EG: if (window.clientWidth > 760) { myTween.start() }. Also keep in mind that this approach will eliminate any possible syncronization issues, but creating many animations is a huge temptation and this will create lots of problems for the old browsers, so keep the function nesting to as minimal as possible as a general rule.

Translate and Position

While the code execution is the fastest for the layout modifiers or what we call box-model, say the position based properties set such as left or top, they may force the entire page layout to change if not absolutelly positioned and thus requires the browser to repaint all elements affected by animated repositioning and their parent elements. On the other side translate doesn't trigger a repaint but involves more complex operations such as more object traversing, string concatenation or check for certain conditions to be met. All of this is because translate is part of transform CSS3 property that has to stack in a single line many more properties such as rotate, skew and scale. An article by Paul Irish explains more about differences in performance between position and translation.

Also any transform property is sub-pixel enabled and requires one or more decimals for accurate and smooth animation, decreasing overall performance. That said and with the emerging high resolution displays, it's safe to speculate that at least translation could be optimized by rounding the values, while scale, rotation and skew requires three decimals.

To put it short left executes faster but requires repaint on every frame while translateX or translate3d execute slower but require no repaint on each animation frame. The winner is left, when it comes to code execution speed, but if we also count the elements' size, the larger size the more favor the translation so the overall winner is translate. The more pixels to recompose in the layout, the more time spent on each frame, and this is why translation is better in most cases, and animated positioning is best to be used as fallback animation for legacy browsers.

Translate, TranslateX and Translate3D

While running a 2D translate:150 animation could score similar performance as translateX:150, interestingly, translate3d:[150,0,0] is slightly faster than the other translations. Some performance tests confirm that translate3d is the prefered property for hardware acceleration. For this reason, translate3d is the winner and KUTE.js always uses it even if you only use translateX or translateY for instance.

Similarly, if you animate the 2D translate this always goes translate(x,y) even if you use translate:150 (only for the X axis) or translate:[150,0] (both X and Y axis), for better performance as well. And by the way, this works great on IE9 and other legacy browsers.

Box Model

We compared position with transition above, but now we are going to talk about other issues related to resizers: width, height, margin, padding and borderWidth or any of their variations. The code execution is super fast, but when resizing the window while animations are running, the browser is also computing the resize handlers, the animation performance is very very low on all browsers, especially when you animate these resize properties. When this toxic combination occurs animating a large amount of elements could crash any browser, no exception, and I think any developer should know about this.

The resize event triggered by these resizer properties can cause some severe issues with legacy browsers such as IE8. These good old browsers don't understand much about Javascript driven layout changes and thus skip/fail to execute any handlers attached to window resize event bubbles.

A workaound for the resizers' effect on the layout would be to use them only for absolute positioned elements, this way the layout will not need to be repainted and the recomposition is limited to the elements themselves. If not, and you are required to provide legacy support, you must DISABLE any resize handlers for IE8 and any other browser that runs slow or crashes. You should also consider not using any resize animation for legacy browsers especially when usability and larger reach is expected.

RGB and HEX

When animating any color property such as (text) color or background-color, KUTE.js always uses/converts to RGB/RGBA, but there is a keepHex:true tween option that overrides that. Still some browsers such as Chrome will still show you the computed style for your color as RGB no matter what. The conversion process will decrease performance, making RGB the winner.

TO and FROMTO

The two main methods for creating animation setups (tween objects) that are coming with KUTE.js are .to() and .fromTo(). While .to() is much more simple and convenient to use, very useful for tween chaining, it has to process the starting values on every .start() delaying the animation for a few miliseconds depending on the browser and hardware, making .fromTo() the winner. On a large amount of elements animating at the same time, these scripting based delays can produce some serious syncronization issues, so caution is advised. In that case you should use .fromTo() properly.

Easing Functions

KUTE.js comes with 3 packs of easing functions: the popular easing functions by Robert Penner, dynamics physics easing functions by Michael Villar and bezier-easing by Gaƫtan Renaudeau. I've worked very hard to optimize the last 2 as much as possible, but they will never beat Robert Penner's functions in any performance test, that's an all time winner.

The point here is that the more accuracy a function offers, the more power needed, and the result is less performance. For instance the cubic-bezier based functions have a 0.0000001 error margin, while the Exponential easing functions by Robert Penner are somewhat glitchy on long page scrolls or translations. Interestingly, some physics based functions perform exceedingly well, and generally the difference in performance is fairly negligible even for large amounts of elements, and have no impact on very few elements.

Garbage Collection

The goal of the development strategy is to be able to execute the script, update layout and repaint, all under 16 miliseconds, so that the animation runs constantly at 60fps. However running some repeatable animations for a large amount of elements would really give garbage collectors a lot of work and thus some frames take more than 16 miliseconds. The more properties and/or elements, the more work.

While garbage collection is a great way modern browsers use to clean the memory, sometimes the garbage collector can jump in anytime, cousing drops in the order of miliseconds. Still, if it's the case, there are ways to help composing the layout faster, but we will see that in the performance testing page.

Property Value Complexity

Just like the high amount of simultaneous animations influence performance, the property value complexity is also an important factor. If we were to compare all the supported properties in terms of complexity, the list would go like this (from most expensive to least): path morphing, regular transform, matrix3d (not yet supported), box-shadow / text-shadow, colors, box model*, unitless props (scroll, opacity).

The * wants to emphasize the fact that box model properties of type resizers have additional performance drawbacks as discussed in a previous chapter.

OSs, Desktops and Mobiles

The performance tests have been performed mainly on Microsoft Windows 8.1 and Ubuntu Linux 14.04 Trusty Tahr with latest nVidia graphics drivers on both OSs, all set up for maximum performance. The browsers are obviously Firefox (both OSs), Google Chrome (both OSs), Opera (both OSs) and IE11 (Win8).

The results show Windows based browsers came better than Ubuntu based ones, mainly because of DirectX and better drivers that greatly improve hardware accelerated graphics, while Linux still faces some noticeable issues with vertical sync among many others, but hey it's a work in progress and it's open source!

The browsers' performance goes like this (from best to poorest): Google Chrome, Opera, Internet Explorer, Firefox. Yes, Firefox is the slowest on Windows OS. I never tested anything on iOS or MAC-OS but I believe Safari performs very well with transforms. Some argue that Safari outperforms Google Chrome due to the latest Webkit upgrade.

Also know that legacy browsers don't support requestAnimationFrame and pollyfills usually replace it with setInterval, a clasic Javascript method that's significantly affecting performance, because it's one of the main causes for lots of JANK.

Another important aspect as far as performance goes, the power saving profiles on Windows OS drops performance for desktop computers and especally laptops. Also when a laptop is unplugged, Windows automatically changes power profile drastically decreasing performance.

As for the mobiles, you must know that even if you have an octacore CPU powered phone or tablet is never going to match a desktop and not even a laptop. For a mobile device these guys recommend to keep everything under 7 miliseconds for the smooth experience that most users expect and that the animation performance of a phone is actually up to 5 times lower than a desktop or laptop. I would stress that having 2 or 3 simoultaneous animations on a phone at a certain point is just about enough.

Another thing to keep in mind is that scrollling on a mobile device is actually hardware accelerated animation and thus compete for power drastically reducing performance for any other CSS or Javascript driven animations. To understand how critical performance is on a mobile device, I highly recommend checking the Google I/O 2014 presentation. Now you understand how much performance really matters.

Remember: do not open any Javascript animation engine performance test with your phone, you may burn your battery, espectially if it's unpluggable.

KUTE.js Project

KUTE.js continues what was started with jQueryTween (removed) and the main goal is to improve usability, compatibility, code quality and performance. KUTE.js includes a jQuery plugin to help you easily implement it in your jQuery applications, and also packs a set of tools such as bezier and physics based easing functions, all elegantly packed for convenience and distributed via CDN.

It all started with a fork of the popular tween.js and ended up having a KUTE.js version 0.9.5 that's very fast, memory efficient and super easy to use.

In the hystory of the making there were consistent contributions of Dav aka @dalisoft for features such as play & pause, Text Plugin, as well as for performance related issues. Generally I would stress that the code is a joint work of me and Dav. Big thanks Dav, well done.

Also I would like to thank Ingwie Phoenix for the npm/Bower and UMD implementations.