加速通过JavaScript将HTML元素附加到div中 [英] Speeding up appending HTML elements into div via JavaScript

查看:80
本文介绍了加速通过JavaScript将HTML元素附加到div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将div中的某些元素添加为列表视图. 我的物品的所有详细信息都存储在一个数组中. 当项目数量少于50左右时,附加过程将花费更少的时间. 但是,当商品尺寸增加到400或更多时,需要花费大量时间 附加我的列表.

I am appending some elements in my div as a list view. All the details of my items are stored in an array. The appending is taking very less time when items are less around 50. However when items size increase to 400 or more the it took lot of time in appending my list.

我如何更快地添加div或快速添加到我的div.

How i can append div little faster or on fly to my div.

结构是这样的.

<div id="main">
<div id="item"></div>
.....
.
.

.
.
<div id="item"></div>

</div>

此主要div是我应用中的其他屏幕.

This main div is as a different screen in my app.

推荐答案

正如 @arete 所述, DocumentFragment 将提高将元素附加到DOM的性能.

As @arete has mentioned, DocumentFragment will increase the performance of appending elements into the DOM.

使用 DocumentFragments 比重复的单个DOM节点注入更快,并且允许您对新元素执行DOM节点操作,而不是通过innerHTML进行批量注入.

Using DocumentFragments is faster than repeated single DOM node injection and allows you to perform DOM node operations on new elements instead of mass-injection via innerHTML.

DocumentFragment接口代表一个最小的文档对象 没有父母它用作文档的轻量级版本. 存储格式正确或潜在格式错误的XML片段.
- MDN

The DocumentFragment interface represents a minimal document object that has no parent. It is used as a light-weight version of Document to store well-formed or potentially non-well-formed fragments of XML.
- MDN

我们可以使用 .appendChild() JavaScript本机方法,如下所示:

We can create an empty DocumentFragment, using document.createDocumentFragment() method, and append the created children by .appendChild() JavaScript native method, as follows:

var frag = document.createDocumentFragment(),
    limit = 400,
    element = 'div',
    clsName = 'item';

for (var i=0; i<limit; i++) {
    var box = document.createElement(element);
    box.className = clsName;
    // Append the child into the Fragment
    frag.appendChild(box);
}

// Finally, append the fragment into the real DOM (touch the DOM just once)
document.getElementById('main').appendChild(frag.cloneNode(true));

工作演示 .

WORKING DEMO.

这是 性能测试 jsPerf

此外,我 更新了小提琴 演示,该演示是由 @Zword 提供,您可能需要考虑.

Also, I updated the fiddle demo which is provided by @Zword, you might want to consider.

这篇关于加速通过JavaScript将HTML元素附加到div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆