1

I have a DOM element (let's call it #mywriting) which contains a bigger HTML subtree (a long sequence of paragraph elements). I have to update the content of #mywriting regularly (but only small things will change, the majority of the content remains unchanged).

I wonder what is the smartest way to do this. I see two options:

  1. In my application code I find out which child elements of #mywriting has been changed and I only update the changed child elements.
  2. I just update the innerHTML attribute of #mywriting with the new content.

Is it worth to develop the logic of approach one to find out the changed child nodes or will the browser perform this kind of optimization when I apply approach two?

Sibiraj
  • 4,486
  • 7
  • 33
  • 57
Oliver Wolf
  • 249
  • 4
  • 8
  • Kind of a broad question, but for my opinion, mothod #2 is more efficient, since it doesn't require any search actions and just replaces the entire text as a whole, while method #1 searches a huge amount of text and also re-constructs it instead of overriding it, a string operation that can be costly. – Koby Douek Aug 09 '17 at 08:30
  • What small things are actually changing? You probably already know which elements to update. Don't construct a HTML string every time only to then find out what changed. Why are you even working with HTML strings? – Bergi Aug 09 '17 at 08:31
  • It really really really depend on each case... I'd just say, use a template framework :) – Salketer Aug 09 '17 at 08:36

2 Answers2

0

No, the browser doesn't do such optimisation. When you reassign innerHTML, it will throw away the old contents, parse the HTML, and place the new elements in the DOM.

Doing a diff to only replace (or rather, update) the parts that need an update can be worth a lot, and is done with great success in rendering libraries that employ a so-called virtual DOM.

However, they're doing that diff on an element data structure, not an HTML string. Parsing that to find out which elements changed is going to be horribly inefficient. Don't use HTML strings. (If you're already sold on them, you might as well just use innerHTML).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Without concdering the overhead of calculating which child elements has to be updated option 1 seems to be much faster (at least in chrome), according to this simple benchmark:

https://jsbench.github.io/#6d174b84a69b037c059b6a234bb5bcd0

Oliver Wolf
  • 249
  • 4
  • 8