{Carrer web log}


Blog about web design & development

About Repaint and Reflow in JavaScript

Tuesday, February 08, 2011 { 10 Comments }

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." – Opera

Basically Reflow is layout change and Repaint color change.

So you get the picture Repaint and Reflow are highly expensive operation for the browser. So you need to minimize the 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.
// before

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; } }


// after – calling innerHTML just once

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 }


Here are more case studies and other examples:

Rendering: repaint, reflow/relayout, restyle

The new game show: "Will it reflow?"

Writing Efficient JavaScript

When does JavaScript trigger reflows and rendering?

Repaint and reflow



RSS IconTwitter icon Twitter icon Twitter icon

About Me <<<

Name: Vladimir Carrer
vladocar [at] gmail.com
Location: Verona, Italy
I'm a web designer, developer, teacher, speaker, generally web addicted ...

My projects <<<

§§Previous Posts <<<

Hand Drawn Icons
 

§Archives <<<

Other Profiles <<<

View Vladimir Carrer's profile on LinkedIn

Content is licensed under a Creative Commons Public Domain License