Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is insertAdjacentHTML so much faster than innerHTML?

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.

like image 732
Peter C Avatar asked Sep 28 '11 21:09

Peter C


People also ask

Why is innerHTML slow?

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.

Is innerHTML fast?

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.

What does insertAdjacentHTML do in JavaScript?

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.

Is it good practice to use innerHTML?

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.


2 Answers

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.

like image 122
Alohci Avatar answered Sep 24 '22 19:09

Alohci


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.

like image 29
user123444555621 Avatar answered Sep 24 '22 19:09

user123444555621