CSS vs. JS Animation: Which is Faster?

website design cyprus

How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps?

This article serves as a point-by-point walkthrough of how JavaScript-based DOM animation libraries, such as Velocity.js and GSAP, are more performant than jQuery and CSS-based animation libraries.

jQuery

Let’s start with the basics: JavaScript and jQuery are falsely conflated. JavaScript animation is fast. jQuery slows it down. Why? Because — despite jQuery being tremendously powerful — it was never jQuery’s design goal to be a performant animation engine:

Note that layout thrashing is what causes stuttering at the start of animations, garbage collection is what causes stuttering during animations, and the absence of RAF is what generally produces low frame rates.

Implementation Examples

Avoiding layout thrashing consists of simply batching together DOM queries and DOM updates:

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

Queries that take place after an update force the browser to recalculate the page’s computed style data (while taking the new update’s effects into consideration). This produces significant overhead for animations that are running over tiny intervals of just 16ms.

Similarly, implementing RAF doesn’t necessitate a significant reworking of your existing codebase. Let’s compare the basic implementation of RAF against that of setInterval:

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 produces the biggest possible boost to animation performance that you could make with a single change to your code.

CSS Transitions

CSS transitions outperform jQuery by offloading animation logic to the browser itself, which is efficient at 1) optimizing DOM interaction and memory consumption to avoid stuttering, 2) leveraging the principles of RAF under the hood and 3) forcing hardware acceleration (leveraging the power of the GPU to improve animation performance).

The reality, however, is that these optimizations can also be performed directly within JavaScript.GSAP has been doing it for years. Velocity.js, a new animation engine, not only leverages these same techniques but also goes several steps beyond — as we’ll explore shortly.

Coming to terms with the fact that JavaScript animation can rival CSS animation libraries is only step one in our rehab program. Step two is realizing that JavaScript animation can actually be faster than them.

Let’s start by examining the weaknesses of CSS animation libraries:

  • Transitions’ forced hardware acceleration taxes GPU’s, resulting in stuttering and banding in high-stress situations. These effects are exacerbated on mobile devices. (Specifically, the stuttering is a result of the overhead that occurs when data is transferred between the browser’s main thread and its compositor thread. Some CSS properties, like transforms and opacity, are immune to this overhead.) Adobe elaborates on this issue here.
  • Transitions do not work below Internet Explorer 10, causing accessibility problems for desktop sites since IE8 and IE9 remain very popular.
  • Because transitions aren’t natively controlled by JavaScript (they are merely triggered by JavaScript), the browser does not know how to optimize transitions in sync with the JavaScript code that manipulates them.

Conversely: JavaScript-based animation libraries can decide for themselves when to enable hardware acceleration, they inherently work across all versions of IE, and they’re perfectly suited for batched animation optimizations.

My recommendation is to use raw CSS transitions when you’re exclusively developing for mobile and your animations consist solely of simple state changes. In such circumstances, transitions are a performant and native solution that allow you to retain all animation logic inside your stylesheets and avoid bloating your page with JavaScript libraries. However, if you’re designing intricate UI flourishes or are developing an app with a stateful UI, always use an animation library so that your animations remain performant and your workflow remains manageable. One library in particular that does a fantastic job at managing CSS transitions is Transit.

JavaScript Animation

Okay, so JavaScript can have the upper hand when it comes to performance. But exactly how much faster can JavaScript be? Well — to start — fast enough to build an intense 3D animation demo that you typically only see built with WebGL. And fast enough to build a multimedia teaser that you typically only see built with Flash or After Effects. And fast enough to build a virtual world that you typically only see built with canvas.

To directly compare the performance of leading animation libraries, including Transit (which uses CSS transitions), head on over to Velocity’s documentation at VelocityJS.org.

The question remains: How exactly does JavaScript reach its high levels of performance? Below is a short list of optimizations that JavaScript-based animation is capable of performing:

  • Synchronizing the DOM → tween stack across the entirety of the animation chain in order to minimize layout thrashing.
  • Caching property values across chained calls in order to minimize the occurrence of DOM querying (which is the Achilles’ heel of performant DOM animation).
  • Caching unit conversion ratios (e.g. px to %, em, etc.) across sibling elements in the same call.
  • Skipping style updating when updates would be visually imperceptible.

Revisiting what we learned earlier about layout thrashing, Velocity.js leverages these best practices to cache the end values of an animation to be reused as the start values of the ensuing animation — thus avoiding requerying the DOM for the element’s start values:

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

The browser could ultimately perform many of these same optimizations itself, but doing so would entail aggressively narrowing the ways in which animation code could be crafted by the developer. Accordingly, for the same reason that jQuery doesn’t use RAF (see above), browsers would never impose optimizations that have even a tiny chance of breaking spec or deviating from expected behavior.

Finally, let’s compare the two JavaScript animation libraries (Velocity.js and GSAP) against one another.

  • GSAP is a fast, richly-featured animation platform. Velocity is a lightweight tool for drastically improving UI animation performance and workflow.
  • GSAP requires a licensing fee for various types of businesses. Velocity is freely open-sourced via the ultra-permissive MIT license.
  • Performance-wise, GSAP and Velocity are indistinguishable in real-world projects.

My recommendation is to use GSAP when you require precise control over timing (e.g. remapping, pause/resume/seek), motion (e.g. bezier curve paths), or complex grouping/sequencing. These features are crucial for game development and certain niche applications, but are less common in web app UI’s.

Velocity.js

Referencing GSAP’s rich feature set is not to imply that Velocity itself is light on features. To the contrary. In just 7Kb when zipped, Velocity not only replicates all the functionality of jQuery’s$.animate(), but it also packs in color animation, transforms, loops, easings, class animation, and scrolling.

In short, Velocity is the best of jQuery, jQuery UI, and CSS transitions combined.

Further, from a convenience viewpoint, Velocity uses jQuery’s $.queue() method under the hood, and thus interoperates seamlessly with jQuery’s $.animate()$.fade(), and$.delay() functions. And, since Velocity’s syntax is identical to $.animate()‘s, none of your page’s code needs to change.

Let’s take a quick look at Velocity.js. At a basic level, Velocity behaves identically to $.animate():

$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, complex scrolling scenes with 3D animations can be created — with merely two 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);

Wrapping Up

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

Before we conclude, remember that a performant UI is about more than just choosing the right animation library. The rest of your page should also be optimized. Learn more from these fantastic Google talks:

One Comment

  • MoffOverony says:

    In reviewing their aim spectrum weighting, the most heavily weighted capricious was tumor thoroughly, which the authors chose to dichotomize at 2 cm It has been observed that IDH remains an uncontrolled favorable prognostic marker after arrangement as a service to echelon and MGMT significance (Sanson et al. 2009) Make 10 M working stocks representing the primers on making a 1:10 dilution of the 100 M stock settling. 3 [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-6/]100 mg clomiphene[/url] menopause symptoms age.
    Prenatal stress diminishes neurogenesis in the dentate gyrus of boy rhesus monkeys Effects of trial handling on the constancy of interleukin 6, tumour necrosis factor-alpha and leptin This reduced troop of DCs and the impairment in their proficiency to prepare and stage antigen results in a decreased in vivo T- chamber feedback [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-5/]cialis soft 40mg[/url] erectile dysfunction medicine. Most of the women who be broached into the surgery on tenterhooks fro chest lumps are minor, that is, below 50—supposing the inexhaustible preponderance of deaths from breast cancer are in women at an end 65 In patients with impaired even out or strength, the misuse of a TLSO may promote sitting, balance, and aristocrats extremity function Automatism components with invo- luntary movements and visual hallucinations come off similarly to infancy truancy [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-8/]10mg provera[/url] menstruation anemia. This cluster algorithm needs the billion of clusters as input parameter, so that the operator purposefulness recollect the most acceptable number quest of the investigated data Sphere of influence of Condition and Kind-hearted Services, Well-being Resources and Services Provision, Motherly and Boy Strength Bureau The get is commonly performed on an outpatient heart, but some physicians or pamper practitioners order the lassie to be admitted in return an overnight check proper for observation [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-2/]200 mg viagra extra dosage[/url] erectile dysfunction kidney transplant. Enteral nutrition is indicated allowing for regarding children who maintain a functioning gastrointestinal leaflet but cannot ingest tolerably nutrients orally This includes the processing of hundreds of thousands of queries in a multi-user scheme in sub- in the second place rejoinder time As it can be observed, during the input of a dose the arteries have higher plasma drug concentrations than those veins not involved in the road of arrival, while during the elimination discontinue the veins show off higher concentrations than the arteries [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-1/]20 mg cialis sublingual[/url] latest advances in erectile dysfunction treatment. Radiographic changes in the clavicle and proximal femur and their use in the resolution of skeletal time eon at death These all fall care of the spread of biotaphonomy, which concerns modifications to remains themselves Power Field An intensity field constitutes the quintessential part of both the living and the nonliving [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-4/]80mg tadapox[/url] erectile dysfunction drugs patents.
    Substance-/Medication-Induced Psychotic Disorders Usually transitory, but can be ruthless CNS syndromes that expand on as a result of sub- carriage power (both illicit and legitimate) and laying open to toxins These include migration of impress (border attrition, band slippage, mooring displacement); tubing-related complications (refuge disconnection, tubing); band leak; esophageal fit; gastroesophageal reflux malady (GERD); irritation of the esophagus or yearning, and port-site infection Bromide of the consequences of deviation of the VHL gene is the overproduction of vascular endothelial broadening consideration (VEGF) under the aegis a works involving a hypoxia-inducible factor [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-7/]5 mg propecia[/url] hair loss laser. He demonstrated singular fearlessness, markedly during the dif?cult terminus period of his disorder, and not ever gave up assumption A edition of the final-year medical curriculum inadver- tently led to the multiple-choice check-up component of the end- of-year assessment having considerably more weight than the clinical component You may be able to compute where the eerie patience of your own specialty or curriculum fits and forecast the probably potency it has on your students’ make a proposal to to erudition [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-10/]20mg vardenafil[/url] erectile dysfunction treatment portland oregon. In this chapter, we sermon the most disputable issues pertaining to the treatment of early-stage EOC focusing on the remedial and prognostic implications of reoperation seeking staging after suboptimal initial surgery, the value and ana- tomic limits of systematic lymph node dissection at leading surgery, the place of minimally invasive surgical techniques, the sort and duration of optimal adjuvant treatment, the value of targeted agents, the implementation of alternative chemotherapy regimens such as dose-dense articulation, opti- mal venture designs, individualized treatment approach, fertility-sparing surgical objectives, and hormone replace- ment and excellence of life The quintessential set forth of this contraption is that a exactly character- ized disposable tonometer investigate resembling a sewing dowel is electromagnetically propelled (induced) to discover into get in touch with with (impression) and then rebound from the corneal surface It is that second road we will attend here, both because it allows us to look more deeply into CODAM as well as frame more competent conjectures about the mostly traverse of deliberate architectures [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-3/]140mg malegra fxt[/url] impotence from diabetes. The wild was evanescent (it disappeared), moved to singular locations, didn’t itch, and looked like measles Our mind can be deceived, our feelings manip- ulated, our perceptions higgledy-piggledy and our consistency tricked with medication Persons with below-the-knee amputations mostly ambulate more without a hitch with prostheses than those with amputations in excess of the knee [url=https://www.theihe.org/conventions/academic-course-part-1/lecture-9/][/url] impotence when trying to conceive.

Leave a Reply