开发者

Which is quicker - on the fly html or creating elements with javascript?

object.innerHTML = "<div class='panel'>foo |</div>"

or

panel = document.createElement ("div");
panel.setAttribute ("class", "panel");
开发者_Python百科panel.innerHTML = "foo |";
object.appendChild (panel);

Say I'm creating a lot of divs on the fly (around a hundred or so), each with event actions, class and id names, which would be the more efficient way? Or does it not matter?


About practicality

Provided you have the correct XSS security in place, I find the ease of use of innerHTML far more important then the speed benefits of potentially using the DOM. Using innerHTML you can simply write HTML.

Actual Speed in Browsers

Depends on the browser, innerHTML is generally faster in IE. DOM manipulation is commonly faster in chrome, but as always it depends on the use case.

The Chrome, Firefox, Safari speeds are so fast its pretty much irrelevant. Considering IE is typically one of the slower browsers, I would advise using innerHTML to help IE along... innerHTML is almost always faster in IE.

source: http://jsperf.com/dom-vs-innerhtml/10

If you are adding tons of elements, innerHTML is very often the way to go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜