What is a DOM?
DOM aka Document Object Model is an interface for web documents. It represents the structure of a document as a tree of objects wherein each object represents a part of the document, such as elements, attributes, and text.
DOM tree is constructed by the rendering engine (i.e Webkit) for parsing HTML document.
DOM allows scripts to access and manipulate the content, structure and style of the document.
Why DOM manipulation is inefficient?
When DOM is manipulated directly it triggers a
reflow and repaint process
in the browser which can be slow.state management in traditional DOM can be challenging and difficult to maintain.
Frequent DOM manipulations can be resource intensive and can create performance bottlenecks on old browsers and mobiles.
How Virtual DOM solves this problem?
Virtual DOM is an abstraction or a lightweight blueprint of the real DOM.
This is maintained by library like React or frameworks like Vue and Angular where each of them has their own implementation for DOM manipulation.
All the manipulations are first made to the Virtual DOM and then the most efficient way is calculated to update the real DOM. Hence, minimizing the number of DOM manipulations.
Advantages of Virtual DOM manipulation
Virtual DOM batches the updates instead of immediately applying state changes to virtual DOM to improve performance.
Reconciliation process compares the updated virtual DOM with previous version to determine minimal set of changes need to bring DOM in sync.
Differences between the old and new Virtual DOM are calculated efficiently using algorithms like tree differencing (e.g., O(n) algorithms such as the "diff" algorithm).
Overall, The Virtual DOM is a blueprint of the actual webpage structure. It helps enhance web performance by minimizing direct updates to the real DOM. By batching changes and efficiently identifying differences, it speeds up rendering of web applications compared to traditional DOM manipulation methods.