Rendering Engine
Rendering Engine
For a more detailed explanation, we need to dive into the way rendering
engines work.
Rendering engines parse the HTML document and create two trees:
the content tree and the render tree. A content tree contains all DOM
nodes. The render tree contains all styling information (the CSSOM)
and only the DOM nodes that are required to render the page.
As soon as the render tree has been created, the browsers goes through
two processes: applying layout and painting each DOM node. Applying
layout means calculating the exact coordinates where a DOM node should
appear on the screen. Painting means actually rendering the pixels and
applying stylistic properties.
Recording a timeline gives you much more insight in what happens under
the hood. I have included the screenshot above as an example to
indicate that painting happens while parsing the document.
Note that the initial paint occurs just before it continues parsing
another part of the document. This process continues until it reaches
the end of the document.
Single threaded
The rendering engine is single threaded. Almost everything, except
network operations, happens in this thread.
Parsing the document halts until this process finishes. You don't
improve the total parsing time by including <script>'s at the end of
the document.
Speculative parsing
The engine parses ahead (and runs the HTML tree construction!) while
scripts are being downloaded and executed. Firefox and Chrome use this
technique.
You can imagine the performance gain if a speculation succeeds (eg. the
DOM wasn't altered by the scripts that are included in the document).
Waiting for the scripts to execute wasn't necessary and the page has
been painted successfully. The downside is that there's more work lost
when the speculation fails.
Luckily for us, very smart people work at these technologies, so even
using document.write properly won't break this process.