javascriptcssrequestanimationframe

Is it useful to use requestanimationframe when javascript updates a class?


Context

I learnt that when I want to keep fluidity on my UI, instead of:

document.querySelector('#div').style.width = '100px';

I can use:

requestAnimationFrame(function() {
  document.querySelector('#div').style.width = '100px';
});

Question

Is it useful to do the same thing for a class change? I mean is this:

requestAnimationFrame(function() {
    document.querySelector('#div').classList.add('big');
});

useful to keep a good UI fluidity?

Note

I have also learned, with the video of Jake about the Javascript event loop, that CSS is applied on a different thread than Javascript, hence my question because since it is Javascript sending the class change, does it is counted as part of the JS event loop or the CSS event loop?


Solution

  • I would say that you shouldn't do this unless you know why you want it.

    Your "fluidity" introduced by RAF is actually caused by moving the change from "do it now" to "do it when you're drawing next".

    Chart of redraws, credit dev.opera.com

    Image credit, as well as a good resource for learning more.