Can I force the browser to render out the DOM changes before continuing javascript execution?

微笑、不失礼 提交于 2019-12-23 09:29:37

问题


I am populating a table with about 500 rows, which takes the browser a few seconds to render, while it appears frozen. This is why I want to display a message asking for the user's patience:

$.ajax({
  url: '{{ search_url }}',
  success: function (response) {
    $('#progress').text('Rendering results, please wait...');
    clear_table();
    populate_table(response);
  }
});

The message isn't displayed - apparently the browser (tested in Chrome 23) buffers all the DOM changes and renders them all in a single go.

As a workaround I found that when I delay populating the table until execution is back to the event loop the message is actually displayed:

$.ajax({
  url: '{{ search_url }}',
  success: function (response) {
    $('#progress').text('Rendering results, please wait...');
    window.setTimeout(function () {
      clear_table();
      populate_table(response);
    }, 0);
  }
});

I wonder if this method will always work or if there is a better technique for this case.


回答1:


This is happening because Javascript execution is single threaded. So until all your JS code is executed the browser will not do anything - in other words it will freeze. To prevent that I suggest you use the jQuery Async plugin (which is just a few lines of code) which will periodically give control back to the browser (by using setTimeout). This prevents the browser from freezing and will display the wait message without any problems.



来源:https://stackoverflow.com/questions/13537096/can-i-force-the-browser-to-render-out-the-dom-changes-before-continuing-javascri

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