jquery:最快的DOM插入? [英] jquery: fastest DOM insertion?

查看:146
本文介绍了jquery:最快的DOM插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对于如何插入更多HTML的感觉很糟糕。
假设我们得到:



var html =< table> ..< a-lot-of-other-标签/> ..< / table>



我想把它放入



$(#mydiv)



以前我做过像



var html_obj = $(html);
$(#mydiv)。 append(html_obj);



jQuery是否正在解析 html 来创建DOM对象?那么这就是我在某个地方读过的东西(更新:)我的意思是我已经阅读了,jQuery解析html手工创建整个DOM树 - 它的废话吗?! ,所以我更改了我的代码:



$(#mydiv)。attr(innerHTML,$(#mydiv)。 attr(innerHTML)+ html);



感觉更快,是吗?这是正确的,这相当于:



document.getElementById(mydiv)。innerHTML + = html ?或者是在背景中做一些额外的昂贵的东西?



也喜欢学习替代品。



但是,如果mydiv中已经有很多,那么您强制浏览器再次解析并再现所有内容(以前的所有内容,以及所有新内容)。您可以通过将文档片段附加到mydiv来避免这种情况:

  var frag = document.createDocumentFragment(); 
frag.innerHTML = html;
$(#mydiv)。append(frag);

以这种方式,只有您的新内容被解析(不可避免),现有的内容不会。 / p>

编辑:我的坏...我发现innerHTML在文档片段上没有得到很好的支持。您可以使用与任何节点类型相同的技术。例如,您可以创建根表节点,并将innerHTML插入到其中:

  var frag = document.createElement('表'); 
frag.innerHTML = tableInnerHtml;
$(#mydiv)。append(frag);


I got this bad feeling about how I insert larger amounts of HTML. Lets assume we got:

var html="<table>..<a-lot-of-other-tags />..</table>"

and I want to put this into

$("#mydiv")

previously I did something like

var html_obj = $(html); $("#mydiv").append(html_obj);

Is it correct that jQuery is parsing html to create DOM-Objects ? Well this is what I read somewhere (UPDATE: I meant that I have read, jQuery parses the html to create the whole DOM tree by hand - its nonsense right?!), so I changed my code:

$("#mydiv").attr("innerHTML", $("#mydiv").attr("innerHTML") + html);

Feels faster, is it ? And is it correct that this is equivalent to:

document.getElementById("mydiv").innerHTML += html ? or is jquery doing some additional expensive stuff in the background ?

Would love to learn alternatives as well.

解决方案

innerHTML is remarkably fast, and in many cases you will get the best results just setting that (I would just use append).

However, if there is much already in "mydiv" then you are forcing the browser to parse and render all of that content again (everything that was there before, plus all of your new content). You can avoid this by appending a document fragment onto "mydiv" instead:

var frag = document.createDocumentFragment();
frag.innerHTML = html;
$("#mydiv").append(frag);

In this way, only your new content gets parsed (unavoidable) and the existing content does not.

EDIT: My bad... I've discovered that innerHTML isn't well supported on document fragments. You can use the same technique with any node type. For your example, you could create the root table node and insert the innerHTML into that:

var frag = document.createElement('table');
frag.innerHTML = tableInnerHtml;
$("#mydiv").append(frag);

这篇关于jquery:最快的DOM插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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