In Firefox, I am inserting text into ~500 DIVs using this code:
$(".divs").text("default"); // ~500 DIVs
On my computer, this consistently takes 9ms if the DIVs are empty. However, this same code consistently takes 18ms if the DIVs already contain text.
Why is it that an empty DIV is 2x faster at inserting text (does jQuery need to empty the DIV first)? And, is there any way to improve the performance of replacing text in a DIV that already contains text?
Note: In IE 7, the speed differences were not as dramatic. Inserting text in an empty DIV was about 1.5x faster.
If you want the fastest solution for all browsers use textContent
if supported and fallback to innerText
/ innerHTML
otherwise [Test] (knowing the gotchas).
/**
* Replaces text for all elements in the given array.
* @param {Array} elems
* @param {String} text
*/
var replaceText = (function(){
var dummy = document.createElement("div");
dummy.innerHTML = "text";
var TEXT = (dummy.textContent === 'text') ? 'textContent' : 'innerText';
return function(elems, text) {
for (var i = elems.length; i--;) {
elems[i][TEXT] = text;
}
};
})();
Faster than jQuery text:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With