Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - jQuery append in loop - DOM does not update until the end

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>');
}

Link to jsfiddle

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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();

Demo: http://jsfiddle.net/Uf4N6/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...