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
541 views
in Technique[技术] by (71.8m points)

dom - Can I use javascript to force the browser to "flush" any pending layout changes?

I have a library that build UI using Javascript, and because of the dynamic content involved I sometimes want to put content out to the browser, examine how the layout was changed to support this and then do a different logic depending on the result. For example: detect if some text is overflowing and truncate it with an ellipsis.

Usually I implement this by putting out the changes, then using window.setTimeout(0) to wait for the layout to update and invoke the rest of the logic. This is obviously sub-optimal as different browsers may either implement a minimal timeout that is too slow to prevent flicker or faster that uses a lot of CPU.

Ideally I would like to do the DOM changes, then force the layout to update synchronously and run the "fix-up" logic immediately inline. Any ideas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

My understanding is that reading any of the CSS properties will force a reflow. You should not need to setTimeout at all.

Excerpt from Rendering: repaint, reflow/relayout, restyle:

But sometimes the script may prevent the browser from optimizing the reflows, and cause it to flush the queue and perform all batched changes. This happens when you request style information, such as

 offsetTop, offsetLeft, offsetWidth, offsetHeight
 scrollTop/Left/Width/Height
 clientTop/Left/Width/Height
 getComputedStyle(), or currentStyle in IE

All of these above are essentially requesting style information about a node, and any time you do it, the browser has to give you the most up-to-date value. In order to do so, it needs to apply all scheduled changes, flush the queue, bite the bullet and do the reflow.

Here's a list of the API calls/properties that will trigger a reflow.

(This answer used to link to a site that 404s now. Here's a link to it in the wayback machine.)


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

...