Search code examples
htmlcssperformancecss-transitions

CSS Transition animation consuming a lot of CPU/GPU


I am implementing a small effect on my website. A random size change in one of the DOM elements.

const theDiv = document.getElementById("the-div");

function animate(){
  const value = Math.floor(Math.random() * 200); 
  theDiv.style.width = value + "px";    
  
  setTimeout(animate, 200);
}

animate();
#the-div { 
  width: 100px;
  height: 50px;
  background-color: brown;
  transition: 0.3s all ease-in-out;
}
<div id="the-div"></div>

However, I have realized that using the CSS transition property to make the size change smoother is consuming a lot of resources, and I don't want this for such "only aesthetic" effect, but on the other hand, I want to feel free to add such effect to my website.

Here is the CodePen for testing:

Click the button "Activate transition" to activate the CSS transition property.

This is my measures using Mac "Activity Monitor" and opening the CodePen in a Chrome browser:

Transition deactivated:

enter image description here

Transition activated:

enter image description here

Using the button "Add div" the effect is increased

Am I doing something wrong? Should I not use CSS transitions for these effects? Or should I just ignore this consuming pick because it is normal, expected, and not dramatic?


Solution

  • Animating width is expensive, as it triggers layout. Have a look here for more details: https://web.dev/animations-guide/#triggers. Try to animate scaleX instead and the performance will be better.

    Also it is bad practice to use the ˋallˋ keyword in transition, i would recommend to be more explicit here and use ˋscaleXˋ.

    Additionally you could also add ˋwill-changeˋ before triggering the animation, so the browser can prepare for the animation. But you should use it sparingly, if at all. For more details, please see: https://developer.mozilla.org/en-US/docs/Web/CSS/will-change?retiredLocale=de (especially the warning at the top)

    Also if you want to trigger the animation with js, you may want to have a look at ˋrequestAnimationFrameˋ: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame