Assume I have an element with id #msg
and on a certain condition I want to add to it a class in order to apply a style e.g. to make the text appear red.
I can do $('#msg').addClass(theclass)
My question is how does the browser react? Does it re-render all of the page or does it re-render that specific element?
A simple text and image are rendered on the screen. From previous explanations, the browser reads raw bytes of the HTML file from the disk (or network) and transforms that into characters. The characters are further parsed into tokens. As soon as the parser reaches the line with <link rel="stylesheet" href="style.
When a web page is loaded, the browser first reads the HTML text and constructs DOM Tree from it. Then it processes the CSS whether that is inline, embedded, or external CSS and constructs the CSSOM Tree from it. After these trees are constructed, then it constructs the Render-Tree from it.
Rendering is a process used in web development that turns website code into the interactive pages users see when they visit a website. The term generally refers to the use of HTML, CSS, and JavaScript codes. The process is completed by a rendering engine, the software used by a web browser to render a web page.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.
With your example (addClass
), it depends what is in the class you add. Adding of the class itself only modifies the attribute on the targeted node.
Browsers are smart enough to only modify the elements that require re-rendering. A technique to minimize the amount of re-renders is to set the element's position: absolute
or display: none
to remove it temporarily from the document flow, make your changes, then re-insert. This is especially important if, eg. you make some element slide down. If the element is in the flow & at the beginning of the DOM tree, every pixel it stretches will cause a re-render.
For the sake of fun, let's make a simple analogy with paper on a desk, in this example with element insertion. The desk is your browser window, □
= paper, _
= empty space. You want to put another sheet at the top left-most position. This is the start-situation:
□ □ □ □
□ □ □ □
_ _ _ _
After you put your new sheet on the desk: (■ = new, ▧ = moved)
■ □ □ □
▧ □ □ □
▧ _ _ _
If the second row was one long roll of paper though (= a full-width div), the entire row would move:
■ □ □ □
▧ _ _ _
▧▧▧▧▧▧▧
If you inserted the sheet on the third row however, no reflow would occur.
Note: This is the theoretical explanation. Its efficiency will vary per browser.
Source: High Performance Javascript, 'Repaints & reflows', p.70.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With