【问题标题】:JavaScript - Browser immediate reflow & repaintJavaScript - 浏览器立即重排和重绘
【发布时间】:2017-06-16 04:53:39
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript dom repaint


【解决方案1】:

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

以这段代码 sn-p 为例... 段落的文本会在警报出现之前更新吗?

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>

【讨论】:

  • 有时 DOM 会更新,屏幕会重新渲染,所以我认为这不是正确的答案。
  • @Fjs 是正确答案。当另一个执行上下文正在运行时,您不能让 JavaScript 执行。这是“事件队列”和回调背后的前提。
  • 是和不是。正如我所说,重绘有时会发生,有时即使 javasript 正在运行也不会发生。
  • 可能是某些事件(即 xhr 正在运行或其他任何事情)导致浏览器重新绘制。
  • 其实,只是没有。 JavaScript 引擎的运行方式由规范定义。并且不依赖于实现。您所遇到的很可能只是代码运行速度的差异。任何事情都可能导致代码运行得更快或更慢。有关示例,请参阅我的更新答案。
【解决方案2】:

所以最后, setTimeout(resolvePromise(...), 0) 帮助了。它为浏览器提供了一些重新绘制的时间。

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 2014-09-25
    • 2017-02-10
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多