所以,我最近一直在尝试一些东西,并在脚本中获得了这段代码:
So, I've been trying stuff lately and got this piece of code in my script:
document.body.bgColor = "red"; alert("hello");但是在Chrome浏览器中,警报对话框会首先弹出,并且只有在我关闭它之后,我的身体背景才会改变.在Firefox中,我得到了预期的行为,将主体背景更改为红色,然后弹出窗口.
But in Chrome, the alert dialog pops up first and only after I close it does the background of my body changes. In Firefox, I get the expected behaviour with body background changing to red followed by the popup.
我知道我们不应该依赖警报和类似的浏览器控件,但是谁能告诉我这是由于行为不在标准范围内还是因为我对上述代码的同步执行的理解是错误的? /p>
I know we shouldn't rely on alerts and similar browser controls but can anyone tell me if this is happening because the behaviour is not in the standards or if it's because my understanding of synchronous execution of the above code is wrong?
推荐答案渲染过程具有其自己的生命周期,并且不会阻止javascript线程.他们俩都独立工作.
The rendering process has a lifecycle of it's own and does not block the javascript thread. They both work independently.
解决方案是暂停" JavaScript执行,以使渲染线程赶上来.这可以通过将简单的setTimeout设置为0
The solution is to "pause" the JavaScript execution to let the rendering threads catch up. This can be done via a simple setTimeout set to 0
document.body.style.backgroundColor = "red"; setTimeout(function() { alert("hey"); }, 0)请注意,bgColor自2003年以来已被弃用,其中 DOM 2级规范.当前设置元素背景颜色的方法是通过element.style.backgroundColor.
Note that bgColor has been deprecated since 2003 with the DOM Level 2 Spec. The current way to set the background color of an element is via element.style.backgroundColor.
更多推荐
为什么在背景更改之前会出现警报?
发布评论