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 > 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.
CodePudding user response:
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
CodePudding user response:
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 > 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.
