Render html immediately after Jquery append

2019-07-26 01:39发布

问题:

I have a loop look like this

for(i = 0; i < 50000; i++){
    $('body').append("<div>lol</div>');
}

In Opera Browser I can See the element div with content "lol" being "appended" in screen.

But in Chrome, Firefox, IE etc I can see the divs only when loop arrive end

How force them to work with Opera work using Js/Jquery or other client-side solution ou POG???

回答1:

First of all, this is really bad practice. Each append forces a relayout and eats performance like cake.

That said, running a loop stalls UI updates. So just use an "async loop", a self referencing function with a timeout call to allow the UI to refresh.

var i = 5000;
var countdown = function () {
    $("body").append("<div></div>");
    if (i > 0) {
        i--;
        window.setTimeout(countdown, 0);
    }
}
countdown();

Edit: Added the actual function call.



回答2:

use a recursive function with a setTimeout. The setTimeout lets the browser update the UI between DOM updates.

function appendDiv(iteration, iterationLimit) {
   $('body').append('<div></div>');
   if(iteration <= iterationLimit) {
      window.setTimeout(appendDiv, 1, iteration + 1, iterationLimit);
   }
}