What is DOM?
Before we start to discover the virtual DOM technology let’s talk a little bit about the basic thing — the original DOM.
This days DOM API is almost cross-platform and cross-browser.
So what’s the problem with it?
The main problem is that DOM was never optimized for creating dynamic UI.
Can we solve this problem? Looks like we can.
Currently, W3C group is working on new Shadow DOM.
Shadow DOM — A W3C working draft standard. This specification describes a method of combining multiple DOM trees into one hierarchy and how these trees interact with each other within a document, thus enabling better composition of the DOM.
Another option is Virtual DOM — Not a standard. Virtual DOM solutions are built on top of standard DOM. They still utilize DOM eventually, but do it as little as possible and very efficiently.
Rather than touching the DOM directly, we’re building an abstract version of it. That’s it. We working with some kind of lightweight copy of our DOM. We can change it as we want and then save to our real DOM tree. While saving we should compare, find difference and change (re-render) what should be changed.
It is much faster than working directly with DOM, because it doesn’t require all the heavyweight parts that go into a real DOM. It works great, but only if we are working with it in a right way. There are two problems to solve: When re-render the DOM and How to do it efficiently.
When. When the data is changed and needed to be updated. But how do we know that the data is changed?
We have two options here:
- First one (dirty checking) — poll the data at a regular interval and check all of the values in the data structure recursively.
- The second option (observable) is to observe for the state change. If nothing has changed, we do nothing. If it changed, we know exactly what to update.
How. What makes it really fast is:
- Efficient diff algorithms.
- Batching DOM read/write operations.
- Efficient update of sub-tree only.
As you understand it’s not an easy thing and implementation of it can be tough. There are some libraries that help us to implement the idea in our projects. The famous one is React JS by Facebook.
React is a library, not a framework. You can’t compare it to Angular or Ember.
Other libraries and Frameworks
- Bobril- Component oriented framework inspired by Mithril and ReactJs.
The idea of Virtual DOM is great and isn’t new actually. We knew for a long time that touching the DOM is expensive. But the implementation of this technique is hard.
Using libraries like React we can boost the performance of our applications and it’s actually very easy to get in.
Thanks for reading :)