Вопрос

I am confused on following style of writing code. I want to know which is the practical and efficient method to insert HTML tag in document.

Javascript:

document.getElementById('demoId').innerHTML='<div>hello world and <a>click me</a> also</div>';

OR

var itd=document.createElement('div'),
    ita=document.createElement('a'),
    idt=document.createTextNode('hello world');
    iat=document.createTextNode('click me');
    idn=document.createTextNode('also');

    ita.appendChild(iat);
    itd.appendChild(idt);
    itd.appendChild(ita);
    itd.appendChild(idn)

    docuemtn.getElementById('demoId').appendChild(itd);

Which is the fastest and best method?

Это было полезно?

Решение

Well just think about what each of them are doing. The first one is taking the string, parsing it and then calling document.createElement, document.appendChild, etc. (or similar methods) based on the output from the parsed string. The second is reducing the work load on the browser as you're stating directly what you want it to do.

See a comparison on jsPerf

According to jsPerf option 1 is approximately 3 times slower than option 2.

On the topic of maintainability option 1 is far easier to write but call me old fashioned, I'd prefer to use option 2 as it just feels much safer.

Edit

After a few results started coming in, the differing results piqued my curiosity. I ran the test twice with each of my browsers installed, Here is a screenshot of the results from jsPerf after all the tests (operations/second, higher is better).

jsPerf results

So browsers seem to differ greatly in how they handle the two techniques. On average option 2 seems to be the faster due to Chrome and Safari's large gap favouring option 2. My conclusion is that we should just use whichever feels the most comfortable or fits best with your organisation's standards and not worry about which is more efficient.

The main thing this exercise has taught me is to not use IE10 despite the great things I've heard about it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top