Every Front-End Development framework is manipulating DOM in one or the other ways. Either they use Virtual DOM or Shadow DOM. My purpose in writing this article is to summaries my knowledge by practically implementing and discussing these approaches.
What is DOM?
DOM(Document Object Model) also known as a tree-structured HTML node interface, where each node represents an HTML element.
What is Virtual DOM?
Javascript plain object representing the structure of actual DOM. At the time of state change frameworks updates objects on background and then render it on DOM tree.
Virtual DOM was introduced and heavily used by React Framework which makes it the most reliable and fast as compared to other frameworks. Here is a quick representation of how Virtual DOM object can be constructed in real world. Point to be noted, you can use different property names.
// Here is an HTML Element
<div id="app">Hello World!</div>
// In virtual dom we can construct this as
const vApp = {
tagName: 'div',
attributes: {
id: 'app',
},
children: [
'Hello World'
]
};
In the above example you can have your own property name, as it hardly matters. Since Virtual DOM is not following any programming interface, which makes it more light weight as compared to actual DOM.
Creating your own Virtual DOM?
To create your own Virtual DOM, you need to have following components:
For understanding the implementation please refer to Jason Yu article at https://dev.to/ycmjason/building-a-simple-virtual-dom-from-scratch-3d05
createElement (tagName, options) this function will return โvirtual elementโ.
render (vNode) will take virtual node and return the corresponding DOM.
mount ($node, $target) will render the vapp on real DOM by replacing data of โโ.
diff (oldVTree, newVTree) will calculate difference between two virtual trees; and return a
patch
function that takes in the real DOM ofoldVTree
and perform appropriate operations to the real DOM to make the real DOM looks like thenewVTree
.diffAttrs (oldAttrs, newAttrs) this will create patch for old attributes to new attributes and removed the other attributes.
diffChildren (oldVChildren, newVChildren) will be used to replace children by considering multiple cases represented in the author article.
main.js will implement our virtual DOM.
Thanks
Since the code is very clearly implemented and explained by Jason Yu. I have only used it from his article. I would like to thank him for sharing his knowledge and helping us to learn new things. Please go and checkout his blog at https://dev.to/ycmjason/building-a-simple-virtual-dom-from-scratch-3d05 for in-depth knowledge.
Summary
Till now we have looked into Basic Concept of Virtual DOM and how we can Create our own Virtual DOM system. Next, I will explain Virtual DOM implementation in React, and Frameworks using Virtual DOM and Shadow DOM. So, stay tuned for my next article in the series on Two Worlds of Front-End Development.
Top comments (0)