如何在触发警报之前进行HTML渲染?

时间:2016-10-17 12:42:33

标签: javascript html

问题其实很简单。如何在警报显示之前更改div的内容?

JSFiddle:

https://jsfiddle.net/n2n5drL2/1/

HTML:

$('#change').click(function(){
  $('#test').text('new content');
  alert('how to make this alert shows after the div changes its content?')
})

JavaScript的:

export default fetchUtil;

module.exports = {
    fetch : fetchUtil,
    post,
    put,
    get,
};

// import code
import fetch from 'utils/fetch';

4 个答案:

答案 0 :(得分:1)

您需要推迟阻塞alert的执行,以便浏览器可以重新呈现更改的DOM。您可以执行此操作with setTimeout and a 0ms timeout

$('#change').click(function(){
  $('#test').text('new content');
  setTimeout(function() {
    alert('how to make this alert shows after the div changes its content?')
  },0);
})

值得注意的是,the specification for alert仅对

  

可选择在等待用户确认消息时暂停。

因此,虽然我个人从未见过用户代理将其视为非阻塞,但规范确实允许它。

答案 1 :(得分:1)

使用alert延迟setTimeout,以便页面有时间重新绘制。 当您使用alert时,所有脚本执行都会在页面上暂停(例如:页面基本上已冻结)。但是当您致电$.text()时,在浏览器完成下一次paint调用之前,文本的实际绘制数据将不会更新。

实际上,通过使用text,您还会触发重新呈现页面的layout阶段。因此,在这种情况下发生的情况是您更新该DOM节点的文本值,并且浏览器将尝试在“免费”时更新图形显示的数据,但由于您立即触发警报,因此浏览器将无法释放你关闭那个警报。通过使用setTimeout,您可以在显示警报之前确保浏览器处于“空闲状态”,以便更新文本数据。

阅读本文以了解有关浏览器如何呈现页面的更多信息:https://developers.google.com/web/fundamentals/performance/rendering/

DEMO:https://jsfiddle.net/n2n5drL2/3/

$('#change').click(function(){
    $('#test').text('new content');
  setTimeout(function() {
    alert('how to make this alert shows after the div changes its content?');
   }, 0);
})

答案 2 :(得分:-2)

更改内容后,您需要等待至少1毫秒:

$('#change').click(function(){
    $('#test').text('new content');
    setTimeout(function() {
        alert('how to make this alert shows after the div changes its content?');
    }, 1);
});

答案 3 :(得分:-3)

默认情况下,但如果没有,则使用settimeout

设置超时



$('#change').click(function() {
  $('#test').text('new content');
  setTimeout(function() {
    alert('how to make this alert shows after the div changes its content?')
  }, 1000);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  Some Text
</div>
<button id="change">
  change
</button>
&#13;
&#13;
&#13;