客户端 JavaScript,创建多个元素并尽快显示每个元素
客户端 JavaScript 代码在一个循环中创建一些元素(大约 50-100 个):
for (var i = 0; i < list.length; i++) {
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
mainObj.appendChild(obj);
}
浏览器渲染存在一些问题。例如,IE 只是冻结直到完成循环,然后立即显示所有元素。有没有办法在 appendChild()
之后立即单独显示每个创建的元素?
Client side javascript code creates some elements (about 50-100) in a cycle:
for (var i = 0; i < list.length; i++) {
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
mainObj.appendChild(obj);
}
There are some problems with browser rendering. For example, IE just freezes until it finishes the cycle, and then shows all elements at once. Is there a way to show each created element separately and immediately after appendChild()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是由于浏览器的单线程性质造成的。直到线程空闲后才会开始渲染。在这种情况下,循环完成并且函数退出。解决这个问题的唯一方法是(某种程度上)使用计时器模拟多个线程,如下所示:
明显的缺点是,这将需要更长的时间才能完成循环,因为它在每次迭代之间拟合渲染。
This is due to the single threaded nature of browsers. Rendering will not begin until the thread becomes idle. In this case, it's when your loop has completed and the function exits. The only way around this is to (sort of) simulate multiple threads using timers, like so:
The obvious drawback is that this will take your loop longer to complete because it's fitting the rendering inbetween each iteration.
使用
setTimeout()
在添加连续条目之间插入延迟。开始吧:
myList 是这样的:
demo: http://jsbin.com/ehogo/4
insert a delay between adding successive entries, with
setTimeout()
.Kick it off with:
where myList is like this:
demo: http://jsbin.com/ehogo/4
我会使用 jQuery 来做到这一点:
jQuery 做得非常快,您甚至不需要费心在创建它们时显示它们,但是您可以通过添加一个计时器来使其更流畅示例显示。
I wold do it like this using jQuery instead:
jQuery does it so quickly, you won't even need to bother about showing as they are created, but you can make it smoother by adding a timer as the example shows.
您希望 DOM 在每个周期后更新是否有特定原因?
如果您在一个 javascript 元素中创建所有元素,并在循环结束时将这一元素添加到 DOM,那么速度会快很多。
Is there a specific reason you want the DOM to be updated after every cycle?
It would be alot faster if you create all the elements in one javascript element, and add this one element to the DOM when the cycle is finished.