TIL Dirty bit systems in browsers
POSTED ON:
Today I learned about the Dirty bit System in Browsers
This is about re-rendering the screen and calcuating the layout.
When the renderer is created and added to the tree, it does not have a position and size. Calculating these values is called layout or reflow.
Process:
- Add the elements
- Calculate the layout (or reflow) <-- this stage
- Paint
HTML uses a flow based layout model, meaning that most of the time it is possible to compute the geometry in a single pass. Elements later "in the flow" typically do not affect the geometry of elements that are earlier "in the flow", so layout can proceed left-to-right, top-to-bottom through the document. There are exceptions: for example, HTML tables may require more than one pass.
Dirty Bit System #
This is done for optimization
In order not to do a full layout for every small change, browsers use a "dirty bit" system. A renderer that is changed or added marks itself and its children as "dirty": needing layout.
There are two flags: "dirty", and "children are dirty" which means that although the renderer itself may be OK, it has at least one child that needs a layout.
First, to explain what a dirty bit is in software:
A dirty bit or modified bit is a bit that is associated with a block of computer memory and indicates whether the corresponding block of memory has been modified. The dirty bit is set when the processor writes to (modifies) this memory
Layout #
Global Layout
When the layout is triggered on the entire render - this is "global" layout.
This can happen as a result of:
-
A global style change that affects all renderers, like a font size change.
-
As a result of a screen being resized
Global layout will usually be triggered synchronously.
Sometimes layout is triggered as a callback after an initial layout because some attributes, like the scrolling position changed.
Incremental Layout
Incremental layout is triggered (asynchronously) when renderers are dirty. For example: when new renderers are appended to the render tree after extra content came from the network and was added to the DOM tree.
Incremental layout is done asynchronously. Firefox queues "reflow commands" for incremental layouts and a scheduler triggers batch execution of these commands. WebKit also has a timer that executes an incremental layout - the tree is traversed and "dirty" renderers are layout out.
Scripts asking for style information, like "offsetHeight" can trigger incremental layout synchronously.
Related TILs
Tagged: browser