Repaints and Reflows: Manipulating the DOM responsibly
This started with a conversation I had with Hong at our friend’s dinner party in July. I tried making small-talk with some new (non-engineer) peeps, but Hong started expounding JavaScript to me and at first I felt bad for being antisocial, but his ideas are always so fascinating that I get sucked in, and soon the other guests have cleared us a wide berth.
One of Hong’s favourite JS topics is about how he prefers not to use jQuery. I tease him for complaining that it’s “it’s too powerful”, but he has a point –– programmers shouldn’t be allowed to easily modify the entire DOM from any part of your program. (In fact, he wrote a JavaScript mini-framework* to render his entire DOM using a single recursive function so that his client-side code hierarchy follows the DOM hierarchy.)
This renders markup swiftly because he keeps the entire node tree in memory while he populates it, then appends it to the DOM just once at the end. When he explained how expensive reflows and repaints were for the browser, I was ashamed that I hadn’t even heard of this concept before, having worked for a year as a Javascript engineer. So I’m documenting it here for beginners like myself.
A repaint, or redraw, goes through all the elements and determines their visibility, colour, outline and other visual style properties, then it updates the relevant parts of the screen.