JavaScript - 浏览器立即回流和重绘

标签 javascript dom repaint

即使有其他代码正在运行,是否可以强制浏览器立即从 JavaScript 执行回流和重绘?

我正在渲染一个进度条,一切都基于异步事件,因此当从服务器或缓存加载某些内容时,DOM 会更新,但有时进度条仍然很快,即 10%,然后它会被替换为常规 DOM文档。

我尝试了所有显示/可见性、无/隐藏、getCompulatedStyle、requestAnimationFrame 的技巧,但没有任何东西强制浏览器进行真正的重绘。它可能会刷新队列并应用所有更改,但不会发生真正的屏幕重绘。

最佳答案

JavaScript 在单线程执行环境中运行。所以不,您不能停止正在运行的执行上下文并执行其他操作。

以此代码片段为例...该段落的文本会在警报出现之前更新吗?

function foo(){
  
  // Note that this timer function is set to run after a zero millisecond delay
  // which effectively means immediately. But, it won't do that because it must
  // first finish executing the current function. So, the timer function will be
  // placed in the event queue and will run as soon as the JS engine is idle. But,
  // we can't know exactly when that will be, we can only ask to run the code after
  // a "minimum" delay time.
  setTimeout(function(){
    document.querySelector("p").textContent = "I've been updated by JS!";
  }, 0);
  
  // The alert will run before the setTimeout function because the alert is part of the
  // current execution context. No other execution context can run simultaneously with this one.
  alert("While you are looking at me, check to see if the paragraph's text has changed yet.");
}

document.querySelector("button").addEventListener("click", function(){
  foo();
});
<button>Click Me</button>
<p>Some content that can be updated by JS</p>

关于JavaScript - 浏览器立即回流和重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41945963/

相关文章:

java - 重绘 JFrame 滞后/弹出

javascript - 如何避免在调整宽度时重新绘制 dom?

javascript - jQuery 上的动画仅执行一次

javascript - 在 PHP 和 JavaScript 之间传递数据?

javascript - Angular : can a controller watch server properties?

javascript - Bootstrap 3 : toggle off-canvas navigation menu doesn't work

c# - 在不使用 WebBrowser 或 HAP 的情况下将字符串或 html 文件转换为 C# HtmlDocument

java.io.FileNotFoundException/employee.xml : open failed ENOENT (No such file or directory) on file read

java - 停止 JButton 在鼠标悬停时重新绘制?

javascript - 条码检测器 DOMException : Barcode detection service unavailable (in Chrome)