About Repaint and Reflow in JavaScript

Tuesday, February 08, 2011 { 10 Comments }



function hndlr(response) {

for (var i = 0; i < response.items.length; i++) { var item = response.items[i]; // in production code, item.htmlTitle should have the HTML entities escaped. document.getElementById("content").innerHTML += "<br>" + item.htmlTitle; } }



function hndlr(response) {

var html = " ";

var y = response.items.length;

for (var i = 0; i < y; i++) { var item = response.items[i]; html += "<br>" + item.htmlTitle; } // making just one Reflow document.getElementById("content").innerHTML = html }

Responses to “About Repaint and Reflow in JavaScript”

Recently I stumbled at this Google Documentation - REST from JavaScript realizing how little web developers are aware about JavaScript performance. I heard about Repaint and Reflow mainly from the work of Stoyan Stefanov and Nicholas Zakas , so I’m writing this short article to help raise the awareness about Repaint and Reflow and JavaScript performance in general.So what is Reflow?A picture is worth a thousand words and probably the video is worth a thousand pictures :)Here is the video:Reflow is the process by which the geometry of the layout engine’s formatting object are computed – Chris Waterson, Mozilla"Repaint - also known as redraw - is what happens whenever something is made visible when it was not previously visible, or vice versa, without altering the layout of the document. An example would be when adding an outline to an element, changing the background color, or changing the visibility style. Repaint is expensive in terms of performance, as it requires the engine to search through all elements to determine what is visible, and what should be displayed." – OperaBasically Reflow is layout change and Repaint color change.So you get the picture Repaint and Reflow arefor the browser. So you need tothe number of the Repaints and Reflows when you do DOM manipulations.Let’s take the example that I mentioned previously:So every time we use insert HTML into the DOM structure we probably triggers reflow. Maybe this isn’t the best example that shows pure resizing of the layout, but we can avoid accessing the DOM multi times.Here are more case studies and other examples: