rokrokss
rokrokss

Reputation: 147

How do browsers build a render tree before </body> tag is in the DOM tree?

I'm studying about how the web browsers work.

I understood as below,

But because the DOM construction stops when meeting <script>, we put <script> right before </body> to finish building Render tree before JS loading.

But doesn't that mean the </body> is not yet in the DOM tree? The writings I saw explains to me that we can finish rendering without waiting for what <script> is doing. I think if that is true, the rendering tree is built without waiting for complete DOM tree but only the CSSOM tree. Because the browsers can browse before </body> is parsed.

Or does it recognize that the only left element is </body> and just ignore it?

Upvotes: 2

Views: 624

Answers (1)

Alohci
Alohci

Reputation: 82976

Your understanding is a little out, but I'll concentrate on the key point.

First the DOM does not contain individual start and end elements or tags. The pair of tags {<body>,</body>} creates a single element called body. Similarly the pair of tags {<span>,</span>} creates a single element called span.

As soon as a start tag is encountered by the parser, the element is created and added to the DOM. If the parsing stalls, the entire DOM created up to that point can be rendered - assuming that there's no render-blocking fetch going on at the time.

As for end tags, they are mostly just used to identify where the element ends so that the next element or text in the markup is not added as a child of the element that's just ended.

However, </body> is a bit of a special case. If the parser encounters tags or text after the </body> tag, the parser will "repair" the DOM by putting the elements and text as children of the body element. That's not to say that the parser ignores the </body> tag entirely - if a comment node immediately follows the </body> tag it will be added as a child of the html element, not the body element.

Upvotes: 2

Related Questions