使用JavaScript将HTML内容附加到div的最快方式 [英] Fastest way to append HTML content to a div using JavaScript

查看:145
本文介绍了使用JavaScript将HTML内容附加到div的最快方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用AJAX从服务器检索邮件的HTML页面。我通过设置其 innerHTML 属性来检索这些消息。

I have an HTML page that uses AJAX to retrieve messages from a server. I'm appending these messages to a as they are retrieved by setting its innerHTML property.

这样工作正常,而文本量很小但是随着它的增长,Firefox会使用所有可用的CPU,并且消息缓慢下降到爬网。我不能使用文本框,因为我想要一些文本被突出显示颜色或使用其他HTML格式。有没有更快的方法来做,这不会导致浏览器锁定?

This works fine while the amount of text is small, but as it grows it causes Firefox to use all available CPU and the messages slow down to a crawl. I can't use a textbox, because I want some of the text to be highlighted in colour or using other HTML formatting. Is there any faster way to do this that wouldn't cause the browser to lock up?

我也尝试过使用jQuery,但从我读过设置.innerHTML比它的.html()函数更快,而且在我自己的经验中也是这样。

I've tried using jQuery as well, but from what I've read setting .innerHTML is faster than its .html() function and that seems to be the case in my own experience, too.

编辑:感知的性能不是一个问题 - 消息已被写入,因为它们被返回(使用Comet)。问题是浏览器开始锁定。内容的数量并不是那么大 - 400-500行似乎是这样做的。该div内没有div。整个事情都在一张桌子里面,但希望不要紧。

Perceived performance is not an issue - messages are already being written as they are returned (using Comet). The issue is that the browser starts locking up. The amount of content isn't that huge - 400-500 lines seems to do it. There are no divs within that div. The entire thing is inside a table, but hopefully that shouldn't matter.

推荐答案

你具体说,您将其附加到同一个父项。你在做这样的事情:

You specifically said that you were appending meaning that you are attaching it to the same parent. Are you doing something like:

myElem.innerHTML += newMessage;

myElem.innerHTML = myElem.innerHTML + newMessage;

因为这是非常低效的(请参阅这个基准: http://jsben.ch/#/Nly0s )。这将导致浏览器首先做一个非常大的字符串concat(这是不是很好),但是更糟糕的是,必须重新解析插入和渲染之前附加的所有内容。比创建一个新的div对象要好得多,使用innerHTML放入消息,然后调用dom方法appendChild来插入新创建的div和消息。那么浏览器只需要插入并呈现新消息。

because this is extremely inefficient (see this benchmark: http://jsben.ch/#/Nly0s). It would cause the browser to first do a very very large string concat (which is never good) but then even worse would have to re-parse insert and render everything you had previously appended. Much better than this would be to create a new div object, use innerHTML to put in the message and then call the dom method appendChild to insert the newly created div with the message. Then the browser will only have to insert and render the new message.

这篇关于使用JavaScript将HTML内容附加到div的最快方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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