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

后端 未结 4 447
感情败类
感情败类 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:29

    Generally, please don't touch DOM too many times. It is a performance killer as you have already observed.

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

    In this way, you touch DOM only once!

    An alternative way is using array.

    var result=[];
    for (i=0; i<5000; i++) {
        result.push('<li>Line Item</li>');
    }
    $('#collection').append(result.join(""));
    
    0 讨论(0)
  • 2020-12-10 03:33

    you need to give back control to the browser every once in a while:

        var current = 0
    
    
        function draw() {
            var next = current + 10
            for(var i = current; i < next; i++) {
                $('#collection').append('<li>Line Item</li>');
            }
            current = next
            setTimeout(draw, 50);
        }
    
    draw();
    
    0 讨论(0)
  • 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('<li>Line Item</li>');
      }
      if (i < 5000) window.setTimeout(appendSomeItems, 0);
    }
    
    appendSomeItems();
    

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

    0 讨论(0)
  • 2020-12-10 03:39

    If that's really what you want to do...

    var i = 0;
    for (i=0; i<5000; i++) {
        setTimeout(function() {
            $('#collection').append('<li>Line Item</li>');
        }, 0);
    }
    
    0 讨论(0)
提交回复
热议问题