Abstract

Animations are taking on the Internet and are an important aspect of each and every website. These animations can range from hover effects to complete interactivity built using WebGL. Animations help improve the usability of an application and provide an effective way of interacting with it. CSS and JavaScript are the most used tools for developing animations on the web; however, each one using them faces the dilemma of which technique to use. Both, CSS and JavaScript, are an integral part of every website and are most commonly used by all web developers. This article analyses all the aspects of CSS and JavaScript animations, which will in turn help you select the right technique for your needs.

CSS Animation

CSS animations work at element level of the web page, and a change to its property will gradually change the element from one style to another. Animation is a CSS property that allows us to animate any HTML element and modify as many CSS properties of the element, for as many times as we want. This provides an easy way to perform simple animation, but the start and end states of the animation are controlled by existing property values, and transitions provide little control to the author on how the animation progresses. At the moment, only WebKit browsers support CSS animations. The unsupported browsers will simply ignore the CSS animation code.

The start time of the animation is determined by the latter of the two instances:

  • The time at which the element that specifies the animation inline is resolved on the web page.
  • The time at which the web page has loaded completely and fires the document load event.

For example, if an animation is specified in the document style sheet (style tag), the animation will begin when document load event is fired. However, if an animation is specified on an element (inline style properties) by modifying the style properties after the document loads, the animation will start once the computed style is resolved. The end of the animation is defined by the combination of the 'animation-duration', 'animation-iteration-count' and 'animation-fill-mode' CSS properties.

In the following example, we will add the animation properties to an element with class=box that you wish to animate:

.box {
	height: 100px;
	width: 100px;
	background-color: black;
	left: 300px;
	top: 250px;
	position: absolute;
	animation-name: bounceIn;
	animation-duration: 5000ms;
	animation-iteration-count: infinite;
	animation-direction: both;
}
@keyframes bounceIn {
	0% {transform: scale(0.1); opacity: 0; }
	10% {transform: scale(1.2); opacity: 0.5; }
	20% {transform: scale(1); opacity: 1; }
	100% {transform: translate(500px); color: red;}
}

JavaScript Animation

JavaScript animations perform gradual changes in the DOM element styles or the canvas objects. The entire animation is split into pieces, and each piece is executed when called by the timer. Since the timer intervals are very small, the animations look continuous and smooth. Creating JavaScript animations is, by comparison, a little more complex than writing CSS animations. But JavaScript animations give more control and power to the developer and the user to dynamically modify the animations on the web page. Most of the modern browsers support JavaScript animations.

Here is a sample code for moving a box (with "id=box") using requestAnimationFrame:

var AnimationDuration = 1000;

function tick() {
	currentTime = Date.now();
	valueTransform = (currentTime - startTime)/AnimationDuration;
	document.getElementById("box").style.transform = 'translate('+ valueTransform*500 +'px)';
	if(valueTransform<= 1)
		window.requestAnimationFrame(tick);
}

function startAnimation()
{
	startTime = Date.now();
	window.requestAnimationFrame(tick);	
}

startAnimation();

CSS vs JavaScript Animation

Now let's analyse various aspects of both animation types to determine who's better.

Dependancy:

JavaScript provides complete control over the animations that users develop. They have the correct tools and commands to handle each step of the animation. It provides an easy way to modify the flow of the animation just by altering a few aspects of the animation. It allows you to seek directly to a particular portion in the animation, alter time scale of the animation, add callbacks at certain points of the animation and bind them to a set of playback events. It provides the power to developers allowing them to start/stop the animation on user actions such as click, key press, mouse move, etc. The sample code provided in the JavaScript section presents the self-independent nature of the JavaScript animation. The startAnimation() function can be called on click of a button.

CSS animations, on the other hand, depend on JavaScript to perform any user specific interactivity. CSS transitions provide a way to define animation effects to be applied to the element at a particular keyframe and CSS animation properties will help attach these effects to a particular element. The start of the animation is dependent on when the web page would load or the element is resolved. There is no way for users to dynamically modify the workflow or interact with the animation. This is where CSS animations are dependent on JavaScript for managing the state of the animations. JavaScript can simply add or remove appropriate classes from the element’s style properties, leaving the browser to handle animations. Consider the following code for example. This sample defines the initial animation for an element with class box and then moves it to a different position when the class=move is added to it.

.box {
  transform: translate(300px, 250px);
  transition: transform 500ms;
  background-color: black;
  height: 100px;
  width:100px;
}
.box.move {
  transform: translate(500px, 250px);
}

JavaScript can be used to add and remove the move class to and from the element, and this control to toggle the animation can be given to the user on click of a button. The following command can be executed to toggle the above defined CSS animation:

var box=document.querySelector('.box');
box.addEventListener('mouseover', function(){
	box.classList.toggle('move');
});

Though CSS transition and animation properties have a wide range support for animation effects, it is dependent on JavaScript to provide user interaction and control.


CPU Performance:

To measure the actual use of CPU to perform animation using each of the technique, we will use an animation created by GreenSock (developers of GreenSock Animation Platform (GSAP) JavaScript animation library)- https://css-tricks.com/myth-busting-css-animations-vs-javascript

  • CSS

The animation presented in the above link allows user to perform animation either using CSS or JavaScript by selecting the respective option from Engine menu. Users can also select the quantity of boxes and the property of the element to animate. Following are the results of CPU utilization for the above animation: Considering the animation is run for 60 seconds, 20 samples are recorded for computation of Average CPU Utilization is as below:

∑CPU utilization samples = 51+58+68+61+61+59+63+77+77+63+70+58+65+63+77+80+80+80+80+80
			 = 1371

Average CPU utilization = (∑CPU utilization samples- ∑Existing CPU utilization)/20
Average CPU utilization = (1371-(20*4))/20
			= 1291/20
			= 64.55%

The value 80 (20*4) is being subtracted from total since the CPU utilization was already at 4% before starting the animation. Thus, 4 will be subtracted from each of the 20 samples recorded.

  • JavaScript

For JavaScript animations, considering the animation is run for 60 seconds, 20 samples are recorded for computation of Average CPU Utilization is as below:

∑CPU utilization samples = 28+30+32+30+30+30+30+32+32+31+30+30+44+30+30+30+30+30+30+30
			 = 619

Average CPU utilization = (∑CPU utilization samples- ∑Existing CPU utilization)/20
Average CPU utilization = (619-(20*4))/20
			= 539/20
			= 26.95%

The value 80 (20*4) is being subtracted from total since the CPU utilization was already at 4% before starting the animation. Thus, 4 will be subtracted from each of the 20 samples recorded.

The above analysis shows that animations using JavaScript are more than 100% efficient and faster than CSS-based animations.


Memory Use:

The memory usage Using the same animation provided in the previous step, the memory usage while performing CSS and JavaScript animations are discussed:

  • CSS
2.4 GB – 2.0 GB = 0.4 GB

Considering the memory usage was already at 2 GB before starting the animation, the CSS animations utilize approximately 400 MB of system memory.

  • JavaScript
2.2 GB – 2.0 GB = 0.2 GB

Considering the memory usage was already at 2 GB before starting the animation, the CSS animations utilize approximately 200 MB of system memory.

The above analysis shows that JavaScript utilize almost half the system memory than CSS, while performing animations. This provides more bandwidth for another process to run and ensure optimal performance.


Speed:

Web animations are limited to the resources allotted by a web browser due to which its performance and speed is completely dependent on how they are being processed. This section presents the aspects that affect the speed of animations using CSS and JavaScript.

  • CSS animations face a substantial lag while starting the animation. This is because it computes the complete layout of the web page along with animation properties and uploads the data to GPU for rendering on the screen. On the other end, JavaScript uses the main browser thread for computation and rendering the animation data on the screen. This helps the animation to initiate quickly without any delay.
  • Though CSS uses hardware acceleration using GPU, only a few CSS properties actually benefit from it to improve performance. When animating top, left, width and height properties of the elements, that affect the document flow, JavaScript is faster across the board.
  • While performing animations that require complex computations and need to modify several element styles, CSS transitions tend to lose their synchronization. This is because, GPU has a limited video memory to upload data. This increases the time for rendering cycle and degrades GPU’s performance. However, this is not true for JavaScript. The browser and CPU itself perform all complex computations. In addition, JavaScript can use GPU for 3D transforms whenever required.

My Pick

CSS transition and animation properties perform best for animations with simple and self-contained state changes. They provide a native solution that allows you to retain animation logic within stylesheets and avoid using JavaScript for modifying animation states. Most of the animations, like the changing name on homepage and fade-in/fade-out, are implemented using CSS in my website.

JavaScript should be used to create stateful animations that require significant control over the flow of the animation. It helps keep the workflow manageable and allows developers to make any modifications quickly.