如何强制浏览器重绘并避免 UI 更新延迟?

How to force browser repaint and avoid UI update delay?

我需要浏览器更新我的 UI,才能完成长时间的(呃)操作。目前浏览器正在等待一切完成后更新 UI,这意味着 UI 冻结 1-2 秒然后更新。

因此,用户单击 UI 中的按钮,然后执行此代码:

$('#mybutton').click(function(e) {

e.preventDefault();// prevent the default anchor functionality

$('#mainctrldiv').css('display', 'none');
$('#otherctrldiv').css('display', 'block');

var img = $('<img id="spareimg" style="display:none;">');
img.attr('src', canvas.getActiveObject().toDataURL()); // This is causing the delay!
img.appendTo('body');
}

canvas.getActiveObject().toDataURL()(一个 FabricJS 函数)占用了时间。我希望在 2 个 div 明显显示给用户之后发生这种情况,他们不会注意到。需要它在所有常用的浏览器中工作! (移动和桌面)。

研究表明,设置后立即读取 css 显示属性会强制浏览器重新绘制,因此我在设置这些属性后直接添加了以下代码,但仍然出现延迟:

$('#mainctrldiv').css('display');
$('#otherctrldiv').css('display');

非常感谢任何建议!

尝试使用setTimeout with zero delay,它会将这些推到线程的末尾。如果零延迟对您不起作用,您也可以尝试添加一些延迟。但我不确定是否是那条确切的线导致了问题,如果 post 关于如何优化和减少的另一个问题时间。

$('#mybutton').click(function(e) {
  e.preventDefault(); // prevent the default anchor functionality
  $('#mainctrldiv').css('display', 'none');
  $('#otherctrldiv').css('display', 'block');
  setTimeout(function() {
    var img = $('<img id="spareimg" style="display:none;">');
    img.attr('src', canvas.getActiveObject().toDataURL()); // This is causing the delay!
    img.appendTo('body');
  }, 0);
}

It's important to note that the function or code snippet cannot be executed until the thread that called setTimeout() has terminated.