Search code examples
csstwitter-bootstrapcss-transformscss-animationsvendor-prefix

How to have CSS animation NOT consume one's entire CPU?


I'm trying to make a loader gif using CSS animation and transforms instead. Unfortunately, the following code converts Firefox's (and sometimes Chrome's,Safari's) CPU usage on my Mac OSX from <10% to >90%.

i.icon-repeat {
   display:none;
  -webkit-animation: Rotate 1s infinite linear;
  -moz-animation: Rotate 1s infinite linear; //**this is the offending line**
   animation: Rotate 1s infinite linear;
}
@-webkit-keyframes Rotate {
  from {-webkit-transform:rotate(0deg);}
   to {-webkit-transform:rotate(360deg);}
}
@-keyframes Rotate {
  from {transform:rotate(0deg);}
   to {transform:rotate(360deg);}
}
@-moz-keyframes Rotate {
  from {-moz-transform:rotate(0deg);}
   to {-moz-transform:rotate(360deg);}
}

Note, that without the infinite linear rotation or the -moz- vendor prefix, the "loader gif"-like behavior is lost. That is, the icon doesn't continuously rotate.

Perhaps this is just a bug or maybe I'm doing something wrong?


Solution

  • I fixed my own problem. Instead of toggling the visibility of the icon, I simply added it then removed it from the DOM. The key thing I hadn't known about using CSS animations is that display:none vs. display:inline consumes CPU either way.

    So instead of that, do this (combined with the CSS in my question above):

    var icon = document.createElement("i"); //create the icon
    icon.className = "icon-repeat";
    
    document.body.appendChild(icon);  //icon append to the DOM
    
    function removeElement(el) {    // generic function to remove element could be used elsewhere besides this example 
      el.parentNode.removeChild(el);
    }
    
    removeElement(icon); //triggers the icon's removal from the DOM