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

后端 未结 4 449
感情败类
感情败类 2020-12-10 03:10

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 app

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 03:38

    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('
  • Line Item
  • '); } if (i < 5000) window.setTimeout(appendSomeItems, 0); } appendSomeItems();

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

提交回复
热议问题