简体   繁体   中英

Why do we need Virtual DOM?

I read the article https://dev.to/karthikraja34/what-is-virtual-dom-and-why-is-it-faster-14p9

There is example of code, example must help us to understand answer on the question - "Why do we need virtual DOM?"

From article:

For example: Let's say we want to render list from an array. we can do it like below.

function generateList(fruits) {
  let ul = document.createElement('ul');
  document.getElementByClassName('.fruits').appendChild(ul);

  fruits.forEach(function (item) {
    let li = document.createElement('li');
    ul.appendChild(li);
    li.innerHTML += item;
  });

  return ul
}
let fruits = ['Apple', 'Orange', 'Banana']
document.getElementById('#list').innerHtml = generateList(fruits)

Now if the list changes, above method can be called again to generate list.

fruits = ['Pineapple', 'Orange', 'Banana']
document.getElementById('#list').innerHtml = generateList(fruits)

In the above code, a new list is generated and it is set in the document. The problem with this approach is only the text of single fruit is changed but a new list is generated and updated to DOM. This operation is slow in DOM. We can change the unoptimised code like below. This will reduce the number of operations in DOM.

document.querySelector('li').innerText = fruits[0]

The final result of both unoptimized and optimized code is same but the cost of unoptimized DOM operation is performance. If the size of list large then you can see the difference. This was the problem we had in older frameworks like backbone js.

So answer to our big question Why do we need virtual DOM? is to solve the above problem.

What modern frameworks like react does is whenever something is changed in the state/props, a new virtual DOM representation will be created and it will be compared with the previous one. In our example, the only change will be "Apple" to "Pineapple". Since only text is changed instead of replacing whole list react will update the DOM by the following code.

document.querySelector('li').innerText = "Pineapple"

Ok, i understad the purpose of Virtual DOM -

By using virtual DOM, we can find out what is changed and with that, we can apply only those changes to real DOM instead of replacing entire DOM

But what prevents us from just writing this without using virtual DOM?

document.querySelector('li').innerText = fruits[0]

But what prevents us from just writing this without using virtual DOM?

 document.querySelector('li').innerText = fruits[0]

This skips over the parts where you are working out that:

  • The first item, and only the first item, in the array has changed
  • When items in the array change then so does the content of the list
  • The first item maps onto the first li item

Generating a virtual DOM from your data and then applying the differences takes care of those steps.

You could write code which does that yourself, but it requires a lot of development time.

There's currently two major approaches to framework/library style rendering:

Virtual Dom

Where a library, such as React, calculates what the rendered DOM should look like in a Virtual Dom, then compares that against the actual DOM and updates the differences.

When events happen (currently in React) they get turned into Synthetic Events which are dispatched from window (might be document now i'm writing it) and then React maps them to appropriate functions which use effects to update data, triggering a re-render of a components part of the virtual DOM - which get's diff'd and synchronised with the real DOM.

DOM

Where a library, such as Angular, uses a class created around Custom Elements to manage the data needed to actually update the DOM, and then updates the DOM within that custom element at various points in the lifecycle.

When events happen, they get dispatched from the element which creates the event, and can bubble if needed, however mostly they get caught by the Custom Element's class to trigger either custom events on the Custom Element, or manage state/data - which in turn gets synchronised with the DOM due to the lifecycle.

Whilst using custom elements alone right now is slightly expensive, however once a Shadow DOM is connected the performance issues move from rendering to either custom developer code or how the browser handles Shadow DOM.

Everyone's got reasons for which they prefer, virtual DOM can be easier when performing server side rendering, where the DOM based approach is more aligned to web standards and leveraging the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM