As alternative you can use insertAdjacentHTML - however I dig into and make some performance tests - (2019.09.13 Friday) MacOs High Sierra 10.13.6 on Chrome 76.0.3809 (64-bit), Safari 12.1.2 (13604.5.6), Firefox 69.0.0 (64-bit) ). The test F is only for reference - it is out of the question scope because we need to insert dynamically html - but in F I do it by 'hand' (in static way) - theoretically (as far I know) this should be the fastest way to insert new html elements.
SUMMARY
innerHTML =
(do not confuse with +=
) is fastest (Safari 48k operations per second, Firefox 43k op/sec, Chrome 23k op/sec) The A is ~31% slower than ideal solution F only chrome but on safari and firefox is faster (!)innerHTML +=...
is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)More info about why innerHTML =
is much faster than innerHTML +=
is here. You can perform test on your machine/browser HERE
let html = "<div class='box'>Hello <span class='msg'>World</span> !!!</div>"_x000D_
_x000D_
function A() { _x000D_
container.innerHTML = `<div id="A_oiio">A: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function B() { _x000D_
container.innerHTML += `<div id="B_oiio">B: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function C() { _x000D_
container.insertAdjacentHTML('beforeend', `<div id="C_oiio">C: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function D() { _x000D_
$('#container').append(`<div id="D_oiio">D: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function E() {_x000D_
let d = document.createElement("div");_x000D_
d.innerHTML = `E: ${html}`;_x000D_
d.id = 'E_oiio';_x000D_
container.appendChild(d);_x000D_
}_x000D_
_x000D_
function F() { _x000D_
let dm = document.createElement("div");_x000D_
dm.id = "F_oiio";_x000D_
dm.appendChild(document.createTextNode("F: "));_x000D_
_x000D_
let d = document.createElement("div");_x000D_
d.classList.add('box');_x000D_
d.appendChild(document.createTextNode("Hello "));_x000D_
_x000D_
let s = document.createElement("span");_x000D_
s.classList.add('msg');_x000D_
s.appendChild(document.createTextNode("World"));_x000D_
_x000D_
d.appendChild(s);_x000D_
d.appendChild(document.createTextNode(" !!!"));_x000D_
dm.appendChild( d );_x000D_
_x000D_
container.appendChild(dm);_x000D_
}_x000D_
_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
.warr { color: red } .msg { color: blue } .box {display: inline}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="warr">This snippet only for show code used in test (in jsperf.com) - it not perform test itself. </div>_x000D_
<div id="container"></div>
_x000D_