开发者

How to detect when the browser has finished updating the view (re-layout, apply any changed CSS)

I have code that I'd like to run that looks something like this pseudocode:

  1. Apply some CSS style to some element

  2. Do some other action

The issue is that I need to not do the 'other action' until after I'm certain that the browser has actually rendered the changed CSS and will be visible to the user.

Although Javascript is single threaded, and if the 'other action' blocks the Javascript from executing further, I'd think that the browser would hopefully still be able to update the view with the new CSS values set in step 1, even if Javascript itself is blocked - but that doesn't appear to be happening (the CSS changes don't show up until after step 2 - in this case a remote 开发者_如何学Cservice call - completes).


Adding to Grezzo's comment, you can use a JS timeout of 0 to ensure the previous line of code has finished executing. This works because it puts whatever is inside the setTimeout's closure at the very end of the internal queue of code to be run. E.g.

// Update CSS  
$('#mydiv').css({'position' : 'relative', 'top' : 0});
setTimeout(function() {
    funcToRunAfterUIUpdate()
}, 0);

I'm too n00b on StackOverflow to post a link, I think, otherwise you can read the "MASTERING THE REFRESH() METHOD" section here: http://cubiq.org/iscroll-4

"Here we placed the refresh call into a zero timeout, doing so we gave the browser the time to refresh itself and the new element dimensions are correctly taken. There are other ways to ensure the browser actually updated the DOM, but so far the zero-timeout has proven to be the most solid."


If you place Javascript code into the head section of your page outside of functions then that Javascript will run before the web page content is loaded. If you place Javascript code outside of functions in the body section of your web page then that Javascript will run as the page is loading (when the loading of the page reaches the code). In both of these instances the entire web page will not have been loaded - particularly if the page contains lots of images.

here you could get more information aboun page events.

http://javascript.about.com/library/bltut31.htm


Have two separate javascript files.... Add the css one where you want to change the css and the other one at the bottom of the page just before the body tag and this will ensure that your js is then executed at later after the page has loaded


Could you use setTimeOut() to call your remote service call function thereby giving a very small time gap for the browser to do it's rendering before doing the function that holds up the rendering?

Do you have an example? jsFiddle perhaps?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜