我可以迫使浏览器中呈现出来的DOM继续JavaScript执行之前改变? [英] Can I force the browser to render out the DOM changes before continuing javascript execution?

查看:137
本文介绍了我可以迫使浏览器中呈现出来的DOM继续JavaScript执行之前改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我填充用约500行,这需要浏览器几秒钟来呈现,而它出现冻结的表。这就是为什么我要显示一个信息,要求用户耐心:

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

不显示消息 - 显然是浏览器(Chrome浏览器测试23)缓存所有的DOM变化,使他们在一个单一的去

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.

推荐答案

这是发生,因为执行的Javascript是单线程的。因此,直到执行所有的JS code中的浏览器将不会做任何事情 - 换言之,它会冻结。以prevent,我建议你使用的jQuery插件异步(这是只是code几行),这将定期把控制权返回给浏览器(使用的setTimeout )。这$ P $冻结pvents浏览器并显示等待消息没有任何问题。

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.

这篇关于我可以迫使浏览器中呈现出来的DOM继续JavaScript执行之前改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆