javascript document.createElement or HTML tags

℡╲_俬逩灬. 提交于 2019-11-30 11:26:00

问题


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?


回答1:


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).

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.



来源:https://stackoverflow.com/questions/15182402/javascript-document-createelement-or-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!