Reputation: 228
I use a lot of CSS animations on my website but performance is not as good as it should be. Therefore I thougt maybe an infinite @keyframe
animation which is only visible at sometimes slows the site down.
I hide it with opacity: 0
for fadeIn
animation and after that I set display
to none
but I am not sure if the animation is rendered nevertheless and consumes resources.
An answer would be highly appreciated.
Upvotes: 2
Views: 214
Reputation: 41675
According to this w3c draft, no; the animation is terminated:
Setting the display property to none will terminate any running animation applied to the element and its descendants.
You can verify this by looking at which animation events are fired. We'll set up an infinitely alternating animation and then you can toggle the element's display with a button:
(d => {
const $ = d.querySelector.bind(d),
div = $("#test-div"),
button = $("#test-button"),
animationEvents = [
"animationstart",
"animationiteration",
"animationcancel",
"animationend",
],
animationEventHandler = e => console.log(e.type);
for (let animationEvent of animationEvents) {
div.addEventListener(animationEvent, animationEventHandler);
}
button.addEventListener("click", e => {
const lastDisplay = div.style.display || "block";
div.style.display = lastDisplay === "block" ? "none": "block";
e.target.textContent = "Toggle display: " + lastDisplay;
});
})(document);
#test-div {
padding: 30px;
animation: test-animation 1000ms alternate infinite steps(2, jump-none);
}
@keyframes test-animation {
from {
background-color: #0f0;
}
to {
background-color: #f00;
}
}
<button id="test-button" type="button">Toggle display: none</button>
<div id="test-div">test div</div>
You can see that animationiteration
stops firing once the element is no longer displayed even though the animation is, "infinite." You could infer from this that the animation runs only while the element is displayed. Indeed, the animation is restarted from 0% when you show the element again.
Upvotes: 2