CSS animations performance comparison between html and css “background-image”
Hello everybody,
Recently I had an issue while creating a rotating loader. I had to make the website logo rotate in the middle of the page, no big issue. I put a container in the center of the page and then created a rotating
class with the following CSS code:
@-webkit-keyframes rotating /* Safari and Chrome */ {
from {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes rotating {
from {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.rotating {
-webkit-animation: rotating 2s linear infinite;
-moz-animation: rotating 2s linear infinite;
-ms-animation: rotating 2s linear infinite;
-o-animation: rotating 2s linear infinite;
animation: rotating 2s linear infinite;
}
Ok, then I assigned the class to an <img>
tag with the “src” attribute set with the logo of the website.
BAM! SLOWY! What the… my previous loader was much faster than this. I looked at my previous loader and I noticed it was based only on CSS rules. Thus I replaced the <img>
tag with a <div>
tag and then added the logo image as a background-image
attribute.
Far better!
I reproduced the same performance gap between different machines so I made this comparison:
<img> rotating logo VS background-image rotating logo
Conclusion:
it’s evident that, at least for the rotation animation, the rendering is faster when the image is a background rather than the “src” attribute of an html image tag. This difference can be evident in heavy load phases (page load) and on mobile devices.
Good to know!
No comments yet.