Image we have a form with a button to make table rows randomly rearrange every second, and a button to sort rows based on some criteria.
I made one example here https://codesandbox.io/s/dawn-water-l2m7g without using any JS libraries.
The way I rearrange the rows in the form is to manipulating the JSON object and regenerate the dom element as a whole
let list = TABLE_DATA; // from the JSON file
...
function startRandom() {
timer = setInterval(function() {
list = list.sort(randomSort);
renderList(list);
}, 1000);
}
function renderList(list) {
const res = list
.map(item => {
return renderRow(xssFilter(item));
})
.join("");
tbody.innerHTML = res;
}
function renderRow(item) {
return `
<tr>
<td>${item.id}</td>
<td><img src="${item.thumbnailUrl}" /></td>
<td>${item.name}</td>
<td>${item.price}</td>
</tr>
`;
}
This website works, but I guess every time renderList
is invoked, the whole tbody
is going to be destroyed and recreated again. Not good performance-wise.
I hope someone can take a look at it and make some optimizations based on the functionalities it has now. For example, maybe DocumentFragment
can help. But I'm not sure.
I don't have much experience dealing with front end development but I feel like this example is not uncommon so I really want to know what is the best practice here and how can we make it better.