Horje
5 Ways to Minimize DOM Interactions for Web Page Optimization

The DOM (Document Object Model) is a hierarchical tree-like structure representing the elements, styles, and content of a webpage. When JavaScript interacts with the DOM, it triggers a series of resource-intensive actions. For instance, every time an element is added or removed, the browser needs to recalculate the layout of the page, leading to delays in rendering the content. To optimize webpage performance, it’s essential to minimize DOM interactions.

Here are five ways to minimize DOM interactions:

1. Batch DOM Interactions

Batching DOM interactions means grouping multiple updates to the DOM into a single operation rather than making individual changes one by one. This approach reduces the number of layout recalculations and repaints, improving performance.

Example:

In this code, we create a document fragment, add list items to it, and then append the entire fragment to the DOM in a single operation.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>My List</title>
</head>
<body>
    <ul id="my-list">
        <!-- List items will be added dynamically with JavaScript -->
    </ul>

    <script>
        // Get the list element by its ID
        const list = document.getElementById('my-list');

        // Create an array of fruits
        const fruits = ['Apple', 'Banana', 'Cherry', 'Orange'];

        // Create a document fragment
        const fragment = document.createDocumentFragment();

        // Loop through the fruits array and append each fruit to the fragment
        fruits.forEach(fruit => {
            const listItem = document.createElement('li');
            listItem.innerText = fruit;
            fragment.appendChild(listItem);
        });

        // Append the fragment to the list in a single operation
        list.appendChild(fragment);
    </script>
</body>
</html>


Output:

Code1

5 ways to Minimize DOM Interactions for Web Page Optimization


2. Use Document Fragments

A document fragment is a lightweight container that can hold DOM nodes. Instead of appending individual nodes to the document, append them to a fragment first. This reduces the number of interactions with the DOM, making your code more efficient.

Example:

In this code, we create a document fragment, add new elements to it, and then append the entire fragment to the container element.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>List of Elements</title>
    <style>
        #myContainer {
            background-color: #f2f2f2;
            padding: 10px;
        }
        .element {
            background-color: #fff;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div id="myContainer"></div>

    <script>
        const container = document.getElementById('myContainer');
        const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

        // Create a document fragment
        const fragment = document.createDocumentFragment();

        // Loop through the data array and append each item to the fragment
        data.forEach(item => {
            const element = document.createElement('div');
            element.classList.add('element');
            element.textContent = item;
            fragment.appendChild(element);
        });

        // Append the fragment to the container in a single operation
        container.appendChild(fragment);
    </script>
</body>
</html>

Output:

5 ways to Minimize DOM Interactions for Web Page Optimization

5 ways to Minimize DOM Interactions for Web Page Optimization

3. Cache DOM References

Caching DOM references is another useful technique to minimize DOM interactions. Every time you query the DOM for an element, the browser has to search through the document to find it, which can be slow. To avoid this, you can cache the reference to the element and reuse it whenever you need to interact with it.

Example:

By caching the reference to the button element, we avoid having to search through the document every time we need to interact with it, which can improve the performance of our code.

HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Button Example</title>
</head>
<body>
    <button id="myButton">Click me</button>

    <script>
        const button = document.getElementById('myButton');

        button.addEventListener('click', function () {
            // Do something when the button is clicked
            alert('Button clicked');
        });
    </script>
</body>
</html>

Output:

5 ways to Minimize DOM Interactions for Web Page Optimization

5 ways to Minimize DOM Interactions for Web Page Optimization


4. Use Event Delegation

Event delegation is a powerful technique that can help reduce the number of event listeners, making your code more efficient. Instead of attaching event listeners to each child element individually, you can attach them to a parent element and delegate the events to the child elements.

Example: 

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Item List Example</title>
    <style>
        .selected {
            color: blue;
            font-weight: bold;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <ul id="item-list">
        <li class="item">Item 1</li>
        <li class="item">Item 2</li>
        <li class="item">Item 3</li>
    </ul>
    <script>
        const itemList = document.getElementById('item-list');

        itemList.addEventListener('click', function (event) {
            if (event.target.classList.contains('item')) {
                event.target.classList.toggle('selected');
            }
        });
    </script>
</body>
</html>

Output:

5 ways to Minimize DOM Interactions for Web Page Optimization

5 ways to Minimize DOM Interactions for Web Page Optimization


5. Use CSS Instead of JavaScript

When possible, use CSS instead of JavaScript to modify the appearance of the page. CSS changes can be handled by the browser’s rendering engine, which is faster and more efficient than modifying the DOM using JavaScript.

Example:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Using CSS Instead of JavaScript</title>
    <style>
        .button {
            background-color: blue;
            color: white;
            padding: 10px;
            border-radius: 5px;
        }
        .button:hover {
            background-color: green;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="button">Click me</div>
</body>
</html>

Output:

By implementing these techniques, you can significantly reduce DOM interactions, leading to faster and more responsive web pages.




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Find Word Character in a String with JavaScript RegExp Find Word Character in a String with JavaScript RegExp
What is the Role of Global RegExp in JavaScript ? What is the Role of Global RegExp in JavaScript ?
How to Add HTML and CSS into PDF ? How to Add HTML and CSS into PDF ?
JavaScript RegExp flags Property JavaScript RegExp flags Property
JavaScript RegExp unicode Property JavaScript RegExp unicode Property

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12