What is DOM diffing?
DOM, also known as the Document Object Model, is a programmatic representation of the contents of a web page. In other words, the content of a web page is represented in the form of
DOM acts as an API (Application Programming Interface) to modify the structure as well as the content of a web page.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>DOM Tree</title> </head> <body> <h1 id="title">Heading</h1> <div class="contact"> <h2>Murtuzaali Surti</h2> <p id="github">@murtuzaalisurti</p> </div> </body> </html>
Here's the visualization of the above DOM tree:
Snippet taken from DOM Visualizer by @bioub
// test this in browser dev tools' console console.log(typeof document) // logs `object`
Painting of DOM
Whenever you update your HTML markup, the DOM gets updated and it needs to be repainted or re-rendered in order to reflect the changes on the screen.
// process of browser rendering DOM tree => CSSOM tree => Render tree => Prepare Layout => Paint Screen
Virtual DOM & Comparision of DOMs
In order to tackle the issue of expensive rendering, some frontend libraries such as React, create a virtual DOM which is similar to the actual DOM but it's efficient because it doesn't have to be painted.
The virtual DOM is created on every state change or re-render in React and is then compared to the previously created virtual DOM. This process of comparing consecutive instances of virtual DOM is known as
If the virtual DOM is different than the previous one, React will calculate which parts of the DOM have been modified and it will update only those parts in the actual DOM.
If there's no change, the actual DOM will remain untouched. You can explore more about the diffing algorithm in react by visiting their documentation.
Want to implement DOM diffing in vanilla JS? You can.