Virtual Dom vs Shadow Dom | ninjasquad
This post explains the DOM, Virtual DOM and Shadow DOM concepts and their differences…
DOM in shorthand for Document Object Model – It’s a way of representing a structured content via objects. HTML, XHTML, XML are some of the ways to write structured content.
By default, when there is any change in the DOM Object, browser re-render the whole page. In this way changes in DOM are expensive in terms of performance.
To solve this issue, new concepts came out. Let’s look at them:-
- The virtual DOM is an in-memory representation of the real DOM.
- Popular UI frameworks React.js and Vue.js, both use Virtual DOM.
- The concept of virtual DOM is mainly to solve performance issue, Here is how:-
- Any update in the DOM first applied to Virtual DOM instead of applying directly to actual DOM. Then it compare the changes against actual DOM through a process call diffing and apply the changes efficiently to actual DOM by only re-rendering the changed elements.
- In additional to that, It allows to collect several changes to be applied at once, so not every single change causes a re-render, but instead re-rendering only happens once after a set of changes were applied from virtual DOM to actual DOM
- You can think of the shadow DOM as a DOM within a DOM. A real DOM can have many shadow DOMs but each share DOM has its own isolated DOM tree with its own elements and styles, completely isolated from the real DOM.
- Concept of Shadow DOM is natively supported by most of the browsers including Firefox, Chrome, Opera and Safari.
- You can make reusable native web components which follows Shadow DOM concept. Implementation and styling of native web component is hidden within the Shadow DOM and having no impact from the outer DOM.
- Polymer LitElement and Vaadin provides open source reusable web components built using shadow DOM concept.
Shadow DOM is not a new concept
Although only recently specified for use by web authors, the shadow DOM has been used by user agents for years to create and style complex components such as form elements. Let’s take the range input element, for example. To create one on the page, all we have to do is add the following element:
That one element results in the following component:
If we dig deeper, we will see that this one
<input> element is actually made up of several smaller
<div> elements, controlling the track and the slider itself.
This is achieved using the shadow DOM. The element that is exposed to the host HTML document the simple
<input>, but underneath it there are elements and styles related to the component that do not form part of the DOM’s global scope.