gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:03:33 24 4
gpt4 key购买 nike

即使有其他代码正在运行,是否可以强制浏览器立即从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com