About a month ago, Firefox 8 implemented the insertAdjacentHTML method, which was added 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.
innerHTML is slow because it has to look for HTML tags in the value, and parse it into DOM nodes. If you're just inserting plain text that doesn't contain any HTML tags, use textContent instead.
In some browsers (most notably, Firefox), although innerHTML is generally much faster than DOM methods, it spends a disproportionate amount of time clearing out existing elements vs.
The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With