Quick Tip – Change CSS Classes and Not Element Styles
You need to change some element’s style as a response to some event. Here is a simple function that contains the problem:
If you read my previous post, you know that every single DOM manipulation including style changes can trigger a reflow. In the previous code we have three potential reflows.
A way to solve the previous problem is using CSS classes instead of manipulating the element’s style. First, you will have to add a new class in your CSS file. Here is the previous style changes as a CSS class:
Now change the previous function to the following function:
Now we will have only one optional reflow instead of three and that is better.
When you are manipulating your DOM you should remember the Browser reflow process even if it is only simple style change. You can’t control when reflows occur but you can minimize their impact on your app performance.