Question:
I saw a framework that worked with Virtual DOM and for that fact it became faster than the others. (framework : facebook reactjs)
What is the advantage and disadvantage of each? How do you work with each one?
Example in pure js
Answer:
Difference between DOM and Virtual DOM
DOM is the representation of the components on the page. You manipulate the DOM in order to manipulate these components (create, recreate, change their state).
Virtual DOM is a framework for manipulating the DOM.
How Virtual DOM Works
Virtual DOM offers three features:
- A representation of the real DOM in the JavaScript language. The actual DOM is then generated from this representation.
- Computation of differences between the real DOM and its representation.
- Patching to update the real DOM according to the new state of its representation.
Thus, using Virtual DOM you:
- 1) Create a DOM representation in the Virtual DOM language;
- 2) Tell the Virtual DOM to generate the real DOM;
- 3) When there is a change in the model, instead of updating the real DOM, you simply send the entire Virtual DOM representation to be regenerated, passing the new model state as a parameter;
- 4) Then you use the comparison engine to get the differences between the Virtual DOM representation and the real DOM;
- 5) And it uses the patch mechanism which will update the real DOM as per the observed differences.
Why Virtual DOM is faster
It's not necessarily faster. It can be faster if your code for checking and manipulating the DOM isn't as efficient as their code.
What are the advantages and disadvantages of each
Since DOM and Virtual DOM are two different things, there is no way to compare them.
What can be compared is the Virtual DOM with another mechanism to manipulate the DOM (pure JavaScript , JQuery or other frameworks like BackboneJS and AngularJS ).
In this case, about the Virtual DOM advantage, although React's advertisement is that it is faster because it uses Virtual DOM, the Virtual DOM's own advertisement says that its main advantage is the organization of the code, which makes it more meaningful, and the ability it gives you to focus on things other than DOM manipulation. Of course, he also claims that he does all this in a very performative way.
Going further in the list of advantages and disadvantages seems to me to enter the opinion, and I can't even comment because I've never used Virtual DOM.
Example of using the Virtual DOM
Retrieved from the Virtual DOM repository on GitHub .
var h = require('virtual-dom/h');
var diff = require('virtual-dom/diff');
var patch = require('virtual-dom/patch');
var createElement = require('virtual-dom/create-element');
// 1: Cria a função que declara como o DOM deve ser
function render(count) {
return h('div', {
style: {
textAlign: 'center',
verticalAlign: 'center',
lineHeight: (100 + count) + 'px',
border: '1px solid red',
width: (100 + count) + 'px',
height: (100 + count) + 'px'
}
}, [String(count)]);
}
// 2: Inicializa o documento
var count = 0; // Precisamos de algum dado do aplicativo. Aqui nós apenas armazenamos um contador.
var tree = render(count); // Nós precisamos de uma árvore inicial (representação do DOM)
var rootNode = createElement(tree); // Cria um nó raiz DOM inicial a partir da representação...
document.body.appendChild(rootNode); // ... e adiciona o nó raiz no documento
// 3: Dispara a lógica de atualização
setInterval(function () {
// atualiza o dado do aplicativo
count++;
// passando como parâmetro o dado atualizado, recria uma árvore completa para representar a view
var newTree = render(count);
// compara a representação recém criada com o DOM real e obtém as diferenças
var patches = diff(tree, newTree);
// aplica as diferenças no DOM real
rootNode = patch(rootNode, patches);
tree = newTree;
}, 1000);
Virtual DOM in the words of its creators:
Translated from the Virtual DOM repository on GitHub .
Manual manipulation of the DOM is a mess and keeping track of the DOM's previous state is difficult. One solution to this problem is to write your code as if you were recreating the entire DOM every time the state changed. Of course, if you actually recreated the entire DOM every time the application's state changed, your application would be very slow and your input fields would lose focus.
Virtual-DOM is a collection of modules designed to provide a declarative way of representing the DOM. So instead of updating the DOM when your application's state changes, you simply create a virtual tree (or "VTRee"), which looks like the state you want the DOM to have. Virtual-DOM will then figure out how to make the DOM look like this virtual tree (with the same state as it) efficiently, without recreating all the DOM nodes.
Virtual-DOM allows you to update the view whenever the state changes by completely recreating the view's VTRee and efficiently updating the DOM so that it looks exactly as you described it. This results in keeping manual DOM manipulation as well as state tracking out of your code, promoting clean and maintainable re-rendering logic for web applications.
Other sources:
-
https://stackoverflow.com/questions/21965738/what-is-virtual-dom
-
http://fluentconf.com/fluent2014/public/schedule/detail/32395