Virtual DOM

Streamlining seamless web updates

What is a DOM?

  1. 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.

  2. DOM tree is constructed by the rendering engine (i.e Webkit) for parsing HTML document.

  3. DOM allows scripts to access and manipulate the content, structure and style of the document.

Why DOM manipulation is inefficient?

  1. When DOM is manipulated directly it triggers a reflow and repaint process in the browser which can be slow.

  2. state management in traditional DOM can be challenging and difficult to maintain.

  3. Frequent DOM manipulations can be resource intensive and can create performance bottlenecks on old browsers and mobiles.

How Virtual DOM solves this problem?

  1. Virtual DOM is an abstraction or a lightweight blueprint of the real DOM.

  2. This is maintained by library like React or frameworks like Vue and Angular where each of them has their own implementation for DOM manipulation.

  3. 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

  1. Virtual DOM batches the updates instead of immediately applying state changes to virtual DOM to improve performance.

  2. Reconciliation process compares the updated virtual DOM with previous version to determine minimal set of changes need to bring DOM in sync.

  3. 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.