DOM manipulation

The more times you access the DOM, the higher the performance cost

The general rule of thumb is to limit DOM accesses and leave the operations on the ECMAScript side as much as possible

Element nodes

Most modern browsers provide apis that only return element nodes and are recommended if available

Because these apis are more efficient to implement than filtering in JavaScript code

For example: Using children is more efficient and has fewer set phases than childNodes

Redraw and rearrange (reflux)

For details, see: HTML backflow and redraw

When performing a series of operations on DOM elements, you can reduce redrawing and reordering by following these steps:

  1. Takes the element out of the document flow
  2. Apply multiple changes to it
  3. Bring the element back into the document

This three-step process triggers two rearrangements — step 1 and step 3. However, there will be many rearrangements in the second step

There are three basic ways to take the DOM out of documentation:

  • Hide elements. Apply the change and redisplay — display: None
  • Build a subtree (createDocumentFragment) outside the current DOM using docuement Fragment and copy it back into the document
<script>
    const fragment = document.createDocumentFragment();
    const fruits = ['Apple'.'Orange'.'Banana'.'Melon'];
    fruits.forEach(fruit= > {
        const li = document.createElement('li');
        li.innerHTML = fruit;
        fragment.appendChild(li);
    });
    document.getElementById('a').append(fragment)
</script>
Copy the code
  • Copy the original element to a node out of the document, modify the copy, and replace the original element when done

Event delegation

When a page has a large number of elements, and each element is bound to an event handler (such as the onclick method), this can affect performance

Each binding event handler comes with a cost:

  • Either you load up the page (more tags or JavaScript code)
  • Or increase the execution time of the runtime

DOM events go through three stages:

  • capture
  • Until the target element is reached
  • The bubbling

DOM event mechanism

  1. Event stream The order in which events are triggered by HTML elements.

  2. Event capture (from outside in)

    • Netscape’s stream of events is called event capture, from the outside in, looking for listener functions, called event capture;
  3. Events bubbling (from inside out)

    • IE’s stream of events is called event bubbling, from the inside out, looking for listeners;
  4. Cancel the bubbling

    • Capture cannot be cancelled, but bubbling can be cancelled

    • E.toppropagation () can interrupt bubble, browser does not go up;

Event delegation

Event delegation uses event bubbling to manage all events of a certain type by specifying only one event handler.

The principle of event delegation

Events start at the deepest node and propagate up;

Performance optimization for event delegation

How it works: Based on the fact that events bubble layer by layer and can be captured by parent elements. With the event broker, you only need to bind a handler to the outer element to handle all events that fire on its children, such as using target to determine the element

Example: Click on a row of apples, the background color of the row changes to orange, and the text changes to orange

If you add an onclick event to each of the LI tags, it will cause a significant performance drain, so you can bind the ul to the onclick event code:

<ul id="a" onclick="aclick()">
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
        <li class="ali">apple</li>
    </ul>
    <script>
        function aclick(e) {
            var e = e || window.event;
            e.target.style.cssText = 'background-color:orange';
            e.target.innerText = 'orange';
        }
    </script>
Copy the code

section

Can be optimized when writing code at ordinary times ① :

To reduce redrawing and backflow, it is best to take this part out of the document stream and then put it back into the document stream after processing it for multiple DOM operations

Points that can be optimized when writing code at ordinary times ② :

With the event broker, you only need to bind a handler to the outer element to handle all events that fire on its children, such as using target to determine the element

Source of Study:High Performance JavaScript- Chinese Version (for learning only)