Improving DOM PerformanceWritten by Jeffrey Bennett
Sounds *suuuuuper* exciting, right? </sarcasm>
But there really is a real-world benefit to this script. If you have a moment, let me explain to you the joys of…
This is where the really technical mumbo jumbo happens, so I won’t be offended [too much] if you decide to leave me. 😭
Here we go!
Document Object Model
The DOM is the invisible structure of all the elements within a webpage. It’s what determines the order, flow, and hierarchy of your webpage based on your HTML markup.
As we know from my previous post, CSS is all the extra fluff and stuff for a website. What I didn’t mention though is, CSS defines and also causes layout, paint, and composite alterations in your DOM.
To reach that buttery-smooth 60 frames per second, you have at most 16.667 milliseconds (1000ms ÷ 60fps = 16.667ms) to create one individual frame.
If rendering takes longer than this extremely short timeframe, the frame will be skipped causing noticeable style reflows and repaints in your webpage. We call this “layout thrashing.”
In more extreme cases, they can crash the browser.
This degrades the user experience for your end-user. And nobody likes bad user experiences!
So, how do you prevent such a thing from happening, Oh Great and Wise Jeffrey?
Combine all of your write operations (mutations) and bring them together at the beginning of your script. Then combine all of your read operations (measurements) and bring those together immediately afterwards. This effectively eliminates layout thrashing completely.
Shebang! Just like that, the universe has achieved equilibrium again.