- How the browser renders the document
- Receives the data (bytes) from the server.
- Parsing by converting into tokens (<, TagName, Attribute, AttributeValue, >) classification.
- Turns tokens into nodes.
- Turns nodes into the
DOMtree. - Build
CSSOMtree from thecss rules. CSSOMandDOMtrees are combined into aRenderTree.- Computes which elements are
visibleand theircomputed styles. - Starting from the root of the dom tree.
Not visibleelements like (meta,script,link) anddisplay: noneare ommited from the render tree.- For each
visiblenode, find the appropriatematching CSSOMrulesand apply them.
- Computes which elements are
- Reflow:
computethe layout of eachvisibleelement (position and size). - Repaint:
rendersthepixelsto screen.
- Repaint
- Occurs when changes affect the visibility.
opacity,color,background-color,visibility.
- Reflow (Layout, LayoutFlush, LayoutThrashing)
- Occurs when the changes affect the layout.
width,position,float.- It is re-calculation of positions and dimensions.
- Has a bigger impact, changing a single element can affect all children, ancestors, and siblings or the whole document.
- Triggers (chagne dom or css, scrolling, user actions
focus). Reflowonly has acostif the document has changed andinvalidatedthestyleorlayout.Something Invalidates+Something Triggers=Costly Reflow.
- Don't change styles by multiple statements, instead:
- Add
class. - Change the
cssText.
- Add
- Batch DOM changes
- Use a
documentFragmentto hold temp changes. - Clone, update, replace the node.
- Hide the element with
display: none(1 reflow, 1 repaint), add 100 changes, restore the display (total 2 reflow, 2 repaint).
- Use a
- Don't ask for computed styles repeatedly, cache them into variable.
- Multiple reads/writes (like for the
heightproperty of an element)- Writes, then reads, from the DOM, multiple times causing document reflows.
- Read(
cached), write(invalidate layout), read(trigger layout). - To fix: read everything first then write everything.
- Multiple reads/writes (like for the
- Resources
- Optimize Selectors
- jQuery uses:
document.querySelectorAll().document.getElementById()faster.- jQuery selector extensions.
- Avoid jQuery selector extensions (
:even,:has,:gt,:eq). - Avoid complex specificity.
- ID-Based Selectors
- jQuery uses:
- Add
styleelement for chaning > 20 instead of.css. - Cache Length During Loops.
- Avoid inspecting large numbers of nodes
document.getElementById('id').getElementsByTagName('*')better thandocument.getElementsByTagName('*').
- Cache DOM values in script variables
var sample = document.getElementById('test')