What is DOM diffing?

Murtuzaali Surti
Murtuzaali Surti

• 2 min read

Updated On

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 objects and nodes.

But why is there a need to represent it in such format? It's required because it allows programming languages such as JavaScript to manipulate or modify the content of a web page.

The DOM

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:

htmlhead#textmeta#texttitle#text#text#textbody#texth1#title#text#textdiv.contact#texth2#text#textp#github#text#text#text

Snippet taken from DOM Visualizer by @bioub

These filled circles represent either a DOM element or a DOM node. DOM can be accessed using the Document API which exposes a global document object for you to manipulate the DOM using JavaScript.

// 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

These repaints can be expensive and lead to performance issues. Repainting can happen more often if the user is interacting with the website because of the site being highly interactive.

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 DOM diffing.

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.


Using Fontsource With 11ty

Previous

Why I love Markdown

Next