Written by

So I recently stumbled onto this lovely JavaScript designed to greatly improve user-interface performance from unorganized or excessive DOM reads and writes.

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…

DOM Rendering

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.

But so does JavaScript.

When you measure and then change DOM elements in JavaScript, it requires a tiny, often insignificant calculation that usually takes a few milliseconds. Any time you so much as touch the DOM, some calculations must be made.

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?

A Solution

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.

However, if you’d prefer to work with an existing JavaScript library, the best tool I’ve found for the job is…

Check out the source code if you’re into that sort of thing.

Shebang! Just like that, the universe has achieved equilibrium again.

This is a very accurate depiction. 😜

Get new posts by email 😎

Unsubscribe anytime. Privacy protected.