1

I'm using javascript to add 160 rows into a table with 10 columns. If I do:

var cellText = document.createTextNode(value);
cell.appendChild(cellText);
row.appendChild(cell);

It takes no time at all to render, but if I switch to cell.innerHTML = value, it takes significantly slower to render. Do we have another option to render HTML elements inside a cell faster?

BTW, the problem appears to be only on IE (IE 11 to be more specific). It's fine in Google Chrome.

I'm using .NET AjaxToolkit.

Johnny
  • 71
  • 1
  • 8
  • 1
    Possible duplicate of [.append VS .html VS .innerHTML performance](https://stackoverflow.com/questions/18393981/append-vs-html-vs-innerhtml-performance) – random_user_name Jan 03 '18 at 23:49

2 Answers2

7

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.

If you need to create complex HTML in the cell, using innerHTML is probably going to be the fastest way, as optimizing HTML parsing has always been a priority of browser designers. But if the HTML is simple (e.g. just a couple of elements) it may be more efficient to create them in Javascript. You'll need to benchmark your specific application to find out where the break-even point is.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Of course, I know that, but I need to insert HTML tags. Any alternatives? – Johnny Jan 04 '18 at 00:12
  • I thought you were trying to do something equivalent to the original code with text nodes. You can create the nodes in Javascript instead of parsing HTML. But I don't know if it will be any faster, usually the HTML parser is best. – Barmar Jan 04 '18 at 00:13
  • No, the original code is very fast. I don't have any problem with it. It's only a problem when there are html tags. – Johnny Jan 04 '18 at 00:32
  • I meant writing your own code that cretes lots of DOM nodes in the cell may be slower than using `innerHTML`. Most browsers have highly optimized HTML parsers. – Barmar Jan 04 '18 at 00:48
  • innerHTML is amazing – Ralph Dingus May 18 '20 at 20:06
0

It's an outstanding bug in IE9, IE10, IE11 and Edge:- https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4561410/

EpochGrinder
  • 109
  • 1
  • 5