Render html immediately after Jquery append

让人想犯罪 __ 提交于 2020-01-05 22:42:41

问题


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


来源:https://stackoverflow.com/questions/11909040/render-html-immediately-after-jquery-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!