Reputation: 137
I have one opportunity to manipulate the DOM of my page before it's styled, rendered and shown to the user. Obviously, I'd love to do all the dynamic fun stuff within this window as DOM manipulations are very expensive after the page as rendered. Since this is primarily targeted at mobile devices, this optimization is valuable to me.
Here's a basic overview / timeline:
function CalledBeforePageRendered(){
DoAsyncDataBaseWorkWithCallBack(AsyncDataBaseCallBack);
DoLocalizationsAndOtherSYNCRONOUSActions();
}
function AsyncDataBaseCallBack(results){
// code that processes the results element
// code that manipulates the DOM *before* it's styled.
}
The problem is that DoAsyncDataBaseWorkWithCallBack
and DoLocalizationsAndOtherSYNCRONOUSActions
finish quickly and then CalledBeforePageRendered
returns and subsequent styling is applied.
After the styling is applied, the page is shown to the user... and then AsyncDataBaseCallBack
gets called
which then applies div tags and other DOM modifications. Only, I needed these modifications to take place before stylization
Is there any way I can make 'CalledBeforePageRendered
' wait for 'AsyncDataBaseCallBack
' to finish before returning? I know that a closure would usually work here, but I do not know how to make a closure work with a callback that is defined outside of the CalledBeforePageRendered
function.
Upvotes: 0
Views: 823
Reputation: 1589
If you are trying to perform a synchronous JavaScript XmlHttpRequest (XHR) call - that's very possible, but assuming your trying to manipulate the DOM on the client side before the page is rendered - why don't you do that on the server side (since it's generating the HTML in the first place). If you can't I highly recommend you don't perform a synchronous JavaScript XHR to update the page before it's rendered. Doing so will lock up the browser window while the XHR is running which can not only add significant latency to page loading - it also frustrates end users (since they experience what appears to be a hard 'lock'). Manipulating the DOM before it's rendered isn't that costly. It's better to return the HTML you want in the first place though - instead of loading more after the page has loaded.
Again - I'd just like to emphasize - try to do this work on the server side (not client). If you can't and need to perform this as a secondary call - add a loading image and let XHR's run asynchronously like most JavaScript libraries pretty much enforce anyways. If I am misunderstanding your goals, please let me know.
Upvotes: 1