Dhananjaya
Dhananjaya

Reputation: 1615

Javascript flow in creating DOM nodes

If I insert some element into DOM tree

document.getElementById("settings-details-form").innerHTML = "<h2 id=\"ddd\">hello</h2>"; 

will the next line of JS code be executed before the DOM updates with the new element ?

What is the JavaScript execution model when doing DOM updates ?

Upvotes: 2

Views: 90

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382304

When the next line is executed

  • the DOM has been updated, you may for example query the dimensions of the element you add
  • the window hasn't been rendered which means you don't have to worry about the user seeing an incomplete state : the window will be rendered when your code ends

Note that most browsers do optimizations : if you don't query the dimensions, for example, they won't be computed until they're needed (for the window rendering, ultimately). That's why it's faster to do a bunch of DOM changes when you don't query the DOM layout in the middle so that the reflow is computed only once (see Mozilla notes on HTML Reflow). The exact flow is highly browser engine dependent but functionally, whatever the browser, the next line of code will see an updated DOM.

Upvotes: 4

Related Questions