jQuery附加循环 - DOM直到结束才更新 [英] jQuery append in loop - DOM does not update until the end

查看:196
本文介绍了jQuery附加循环 - DOM直到结束才更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当循环遍历一个大集合并将其附加到DOM时,只有在追加所有项目之后,DOM才会刷新。为什么每个 append()调用后,DOM不会更新?我可以强制DOM在每次追加后刷新(也可能在每个n个追加之后)?

When looping over a large collection and appending it to the DOM, the DOM only refreshes after all items have been appended. Why doesn't the DOM update after each append() call? Can I force the DOM to refresh after each append (or maybe after each n number of appends)?

var i = 0;
for (i=0; i<5000; i++) {
    $('#collection').append('<li>Line Item</li>');
}

链接到jsfiddle

注意:我明白,通过将所有元素附加到本地来实现更好的性能(避免DOM回流)变量,然后将该变量附加到DOM。但是我希望前n个元素在屏幕上渲染,然后是下一个n等等,直到所有元素都被渲染。

NOTE: I understand that better performance (avoiding DOM reflow) can be achieved by appending all elements to a local variable, and then appending that variable to the DOM. But I want the first n elements to render on the screen, then the next n, etc. until all elements are rendered.

推荐答案

JavaScript正在运行时,浏览器中的大部分内容都会停止。这包括例如DOM渲染,事件处理,图像动画。

Most everything in the browser stops while a Javascript is running. This includes for example DOM rendering, event handling, image animation.

导致DOM渲染的唯一方法是结束Javascript。您可以使用 setTimeout 方法在更新后再次启动代码:

The only way to cause the DOM to be rendered is to end the Javascript. You can use the setTimeout method to start code again after the update:

var  i = 0;

function appendSomeItems() {
  for (var j=0; j<50; i++, j++) {
    $('#collection').append('<li>Line Item</li>');
  }
  if (i < 5000) window.setTimeout(appendSomeItems, 0);
}

appendSomeItems();

演示: http: //jsfiddle.net/Uf4N6/

这篇关于jQuery附加循环 - DOM直到结束才更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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