Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Why is element not being shown before alert?

In this simple example https://jsfiddle.net/4rsje4b6/1/ why is the #test element not being shown before the alert appears?

Shouldn't the jQuery css() method be syncronous?

#test {
  display: none;
}
<span id="test">Element</span>
$("#test").css("display", "inline");
alert("Showed element!");

UPDATE:

This behavior is manifesting for me on Chrome Version 52.0.2743.116 m, Windows 10.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It changes the style synchronously, and you will notice that if you read back the value on the next line and show it.

$("#test").css("display", "inline");
alert("Showed element!" + $("#test").css("display"));

But the change of the style object triggers a repaint request message to the page renderer, and that is handled as soon as the browser becomes idle, which is after this script routine has ended.

It depends on the browser, though. In Edge it works fine, and the element is shown right away but in Chrome and Vivaldi it is not.

Another test to see how browsers handle this: If you resize the browser window, JSFiddle will scale (each of the areas keeps the same relative size). If you resize the Vivaldi browser with the alert open, it doesn't do that. In fact if you make it small, then show the alert, then make it larger, you just get a grey area in the new space until you close the message box. In Edge, the fiddle will just resize in the background, even though the entire browser window is grayed out, so it's not just a matter of the time of processing, but more that Chrome completely freezes the page when an alert is open.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...