js div前插入html,javascript - Inserting HTML into a div - Stack Overflow

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.

LRABc.png

SUMMARY

The A 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 (!)

The B innerHTML +=... is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)

The D jQuery is second slow on all browsers (Safari 14 op/sec, Firefox 11k op/sec, Chrome 7k op/sec)

The reference solution F (theoretically fastest) is not fastest on firefox and safari (!!!) - which is surprising

The fastest browser was Safari

More info about why innerHTML = is much faster than innerHTML += is here. You can perform test on your machine/browser HERE

let html = "

Hello World !!!
"

function A() {

container.innerHTML = `

A: ${html}
`;

}

function B() {

container.innerHTML += `

B: ${html}
`;

}

function C() {

container.insertAdjacentHTML('beforeend', `

C: ${html}
`);

}

function D() {

$('#container').append(`

D: ${html}
`);

}

function E() {

let d = document.createElement("div");

d.innerHTML = `E: ${html}`;

d.id = 'E_oiio';

container.appendChild(d);

}

function F() {

let dm = document.createElement("div");

dm.id = "F_oiio";

dm.appendChild(document.createTextNode("F: "));

let d = document.createElement("div");

d.classList.add('box');

d.appendChild(document.createTextNode("Hello "));

let s = document.createElement("span");

s.classList.add('msg');

s.appendChild(document.createTextNode("World"));

d.appendChild(s);

d.appendChild(document.createTextNode(" !!!"));

dm.appendChild( d );

container.appendChild(dm);

}

A();

B();

C();

D();

E();

F();

.warr { color: red } .msg { color: blue } .box {display: inline}

This snippet only for show code used in test (in jsperf.com) - it not perform test itself.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值