是否可以强制浏览器立即执行重排&从JavaScript重新绘制,即使有其他代码在运行?
我正在渲染一个进度条,所有内容都基于异步事件,所以当从服务器或缓存中加载某些内容时,DOM会更新,但有时候进度条仍然很快,即10%,然后用常规DOM替换文档。
我用display / visibility none / hidden,getComputedStyle,requestAnimationFrame尝试了所有这些技巧,但没有任何东西强迫浏览器进行真正的重绘。它可能会刷新队列并应用所有更改,但不会对屏幕进行真正的重新绘制。
答案 0 :(得分:0)
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>
&#13;
答案 1 :(得分:0)
所以最后,setTimeout(resolvePromise(...),0)帮助了。它为浏览器提供了一些重新绘制的时间。