Createelement() Vs. Innerhtml When To Use?
Solution 1:
Adding to the DOM n times takes n times more time than adding to the DOM a single time. (:P)
This is the logic I'm personally following.
In consequence, when it is about to create, for instance, a SELECT element, and add to it several options, I prefer to add up all options at once using innerHTML than using a createElement call n times.
This is a bit the same as to compare BATCH operation to "one to one"... whenever you can factorise, you should!
EDIT: Reading the comments I understand that there's a feature (DOM DocumentFragment) that allow us saving such overhead and at the same time taking advantage of the DOM encapsulation. In this case, if the performances are really comparable, I would definitely not doubt and chose the DOM option.
Solution 2:
I thought I read somewhere that the createElement and appendElement is faster. It makes sense, considering document.write() and innerHTML have to parse a string, and create and append the elements too. I wrote a quick test to confirm this:
<html><body><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script>functioninner() {
var test = '';
for (var i=0; i<10000; i++) {
test += '<p><a href="../" target="_blank">bogus link</a> with some other <strong>stuff</strong></p>';
}
console.time('innerHTML');
document.getElementById('test').innerHTML = test;
console.timeEnd('innerHTML');
}
functionjq() {
var test = '';
for (var i=0; i<10000; i++) {
test += '<p><a href="../" target="_blank">bogus link</a> with some other <strong>stuff</strong></p>';
}
console.time('jquery');
jQuery('#test').html(test);
console.timeEnd('jquery');
}
functioncreateEl() {
var dest = document.getElementById('test');
console.time('createel');
//dest.innerHTML = '';//Not IE though?var repl = document.createElement('div');
repl.setAttribute('id','test');
for (var i=0; i<10000; i++) {
var p = document.createElement('p');
var a = document.createElement('a');
a.setAttribute('href','../'); a.setAttribute('target','_blank');
a.appendChild(document.createTextNode("bogus link"));
p.appendChild(a);
p.appendChild(document.createTextNode(" with some other "));
var bold = document.createElement('strong');
bold.appendChild(document.createTextNode("stuff"));
p.appendChild(bold);
repl.appendChild(p);
}
dest.parentNode.replaceChild(repl,dest);
console.log('create-element:');
console.timeEnd('createel');
}
</script><buttononclick="inner()">innerhtml</button><buttononclick="jq()">jquery html</button><buttononclick="createEl()">Create-elements</button><divid="test">To replace</div></body></html>
In this example, the createElement - appendChild method of writing out HTML works significantly faster than innerHTML/jQuery!
Post a Comment for "Createelement() Vs. Innerhtml When To Use?"