dimanche 12 août 2018

Speed difference between inserting html and changing display style property

Assuming you have a relatively small piece of html (let's say under 100 tags and <4KB in size) and you want to occasionally display and hide it from your user (think menu, modal... etc).

Is the fastest approach to hide and show it using css, such as:

//Hide:
document.getElementById('my_element').style.display = 'none';

//Show:
document.getElementById('my_element').style.display = 'block';

Or to insert and remove it:

//Hide
document.getElementById('my_element_container').innerHTML = '';

//Show:
const my_element_html = {contents of the element};
document.getElementById('my_element_container').innerHTML = my_element_html;

// Note: insertAdjacentHTML is obviously faster when the container has other elements, but I'm showcasing this using innerHTML to get my point across, not necessarily because it's always the most efficient of the two.

Obviously this can be benchmarked on a case by case basis, but, with some many browser versions and devices out there any benchmakrs that I'd be able to run in a reasonable amount of time aren't that meaningful.

I've been unable to find any benchmarks related to this subject.

Are there any up to date benchmarks comparing the two approaches ? Is there any consensus from browsers developers as to which should, generally speaking, be preferred when it comes to speed.




Aucun commentaire:

Enregistrer un commentaire