0

Please forgive confusing question above...

I have a dashboard that will fetch json data with ajax for every couple seconds. The current solution is it will clear the dashboard, and get the json data and combine them with html, so is kind of like this:

$.ajax({
    ....
}).done((res) => {
    $mainBody.html('');
    for (let i = 0; i < res.length; i++){
        let ele = '<div class="...">  with adding the json data  </div>';
        $mainBody.append(ele);
    }
})

Each ele will contain around 55 lines of html code, and most of time will loop for more than 20 times to finish adding all elements.

And now I want to take a more object-oritented approach to this dashboard and considering to use document.createElement() for all elements, and then to set their innerHtml directly after every fetch. But I'm not so sure on efficiency wise and speed, which solution should I use.

YZY
  • 47
  • 1
  • 7

2 Answers2

1

The most effective would be to use document.createElement because in addition to creating the element you have control of all its properties, that is, you don't need to use querySelector, just store the created element in a variable and then add it to the DOM, innerHTML reconstructs the entire DOM while appendChild only the part of the DOM where the parent element is, besides that you have no control over the element or its children.

const myElement = document.createElement("span");
myElement.textContent = "Hello world!";
myElement.className = "message";

document.body.appendChild(myElement);
body {
  text-align: center;
}

.message {
  font-weight: bold;
  font-size: 32px;
  color: #222;
}

"innerHTML += ..." vs "appendChild(txtNode)"

https://betterprogramming.pub/whats-best-innertext-vs-innerhtml-vs-textcontent-903ebc43a3fc

Gamedroit
  • 379
  • 2
  • 6
-1

Best would be to make one big string in the loop, and assign the innerHTML once at the end.

let html = res.map(el => `<div class="..."> add json data in here </div>`).join('');
$mainBody.innerHTML = html;

The browser is very efficient at parsing HTML, but you should just do it once. Your method requires converting the DOM back to HTML and re-parsing it each time through the loop.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I see, but then after the page loaded, I have an interval that will re-fetch the data and update the dashboard, will this still be efficient compare to I use `document.createElement` at first, then edit the `innerHTML` for each element? – YZY Jan 21 '22 at 23:05
  • If you're appending to an existing element rather than replacing it, use `insertAdjacentHTML()` for the new elements. – Barmar Jan 21 '22 at 23:06
  • You'd need to benchmark it, but depending on the size this can be more efficient than calling `createElement` for lots of elements. – Barmar Jan 21 '22 at 23:06
  • Think about how quickly an enormous HTML document loads from the network. The parsing code is highly optimized. – Barmar Jan 21 '22 at 23:07