开发者

How is insertAdjacentHTML so much faster than innerHTML?

开发者 https://www.devze.com 2023-04-08 22:17 出处:网络
About a month ago, Firefox 8 implemented the insertAdjacentHTML method, which was ad开发者_运维百科ded to IE4 along with innerHTML. According to this benchmark, insertAdjacentHTML is usually an order

About a month ago, Firefox 8 implemented the insertAdjacentHTML method, which was ad开发者_运维百科ded to IE4 along with innerHTML. According to this benchmark, insertAdjacentHTML is usually an order of magnitude faster than innerHTML.

I assume both call the same HTML parser, so why is the difference that dramatic? insertAdjacentHTML is a simple method call, whereas innerHTML is a getter/setter and there's probably a bit of overhead for that, but I would never imagine that much.


work.innerHTML += "<span>test</span>"; is equivalent to work.innerHTML = work.innerHTML + "<span>test</span>";, i.e. each time it runs it has to serialise all the existing contents of work and then reparse the whole lot, plus the additional span.

work.insertAdjacentHTML("BeforeEnd", "<span>test</span>"); is only parsing the one span each time and then attaching the small document fragment to the DOM.


The innerHTML setter will have to remove all existing child nodes prior to adding new ones.

Don't know if this is the only reason, but that's certainly a factor.

0

精彩评论

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

关注公众号