0

I am trying to understand when to use the virtual DOM concept and when not to. After reading the following answer on SO (https://stackoverflow.com/a/28199479/4584825) I have got an impression that the virtual DOM is to be used only when we want to refresh the entire DOM tree. Is that true ?

Because take the following code snippet-:

<html>
<body>
<div id="a">Hello</div>
</body>
</html>

Now if I want to replace the content of the div with say World. I would write something like-:

document.getElementById("a").innerHTML = World;

In this mirrors typical AJAX scenarios where only part of the page is refreshed. How would the virtual DOM help me in this case ? Anyways I am targeting a specific element or set of elements, so what difference does it make that whether I am using a virtual DOM or the real DOM ?

Community
  • 1
  • 1
Heidi
  • 75
  • 10
  • The virtual DOM would help you if you did `document.body.innerHTML = '
    World
    '` - because it could figure out that the actual DOM only needs to update `#a`.
    – Bergi Mar 03 '15 at 20:33
  • @Bergi So if I am careful I can actually get better performance from not using a virtual DOM rather than using one right ? Because in the example I have given above extra time would be wasted for figuring out what to replace. – Heidi Mar 04 '15 at 14:20
  • Yes, by manually caring about everything yourself you can always get better performance :-) However, always going down into details will make your code uncomprehensible, and using a library like virtual-dom to do this stuff for you lets you write more declarative and correctly-working code - as the library will be tested on its own. – Bergi Mar 04 '15 at 14:46
  • Notice that in the above example you could further optimize (make less DOM changes) by `document.getElementById("a").textContent = "World";` (not needing a html parser) or even `document.getElementById("a").firstChild.value = "World";` (even reusing the text node). – Bergi Mar 04 '15 at 14:48

0 Answers0