views:

3032

answers:

3

Here is the situation. I have some javascript that looks like this:

function onSubmit() {
    doSomeStuff();
    someSpan.style.display="block";
    otherSpan.style.display="none";
    return doLongRunningOperation;
}

When I make this a form submit action, and run it from a non IE browser, it quickly swaps the two spans visibility and run the long javascript operation. If I do this in IE it does not do the swap until after onSubmit() completely returns.

I can force a dom redraw by sticking an alert box in like so:

function onSubmit() {
    doSomeStuff();
    someSpan.style.display="block";
    otherSpan.style.display="none";
    alert("refresh forced");
    return doLongRunningOperation;
}

Also, the obvious jquery refactoring does not affect the IE behavior:

function onSubmit() {
    doSomeStuff();
    $("#someSpan").show();
    $("#otherSpan").hide();
    return doLongRunningOperation;
}

This behavior exists on IE8 and IE6. Is there anyway to force a redraw of the DOM in these browsers?

+5  A: 

Mozilla (maybe IE as well) will cache/delay executing changes to the DOM which affect display, so that it can calculate all the changes at once instead of repeatedly after each and every statement.

To force an update (to force an immediate, synchronous reflow or relayout), your javascript should read a property that's affected by the change, e.g. the location of someSpan and otherSpan.

(This Mozilla implementation detail is mentioned in the video Faster HTML and CSS: Layout Engine Internals for Web Developers.)

ChrisW
interesting. didn't know this.
meder
I will give that a try in the AM.
Justin Dearing
I tried this, but could not get it to work.
Justin Dearing
At time 37:15 in the **Mozilla** video I cited, he suggests asking for "offset top" or "offset left" which require that the layout be up-to-date.
ChrisW
Thank you sooo much!! This saved me. BTW, the guy doing the video sucks at public speaking.
HaxElit
+2  A: 

Can your longRunningOperation be called asynchronously?

misteraidan
You ended up being right, but with some work. I called the long running operation asynchronously, had my submit event return false, and then the async event really submits my form. This lead to proper behavior in all browsers, but took a lot of work and kinda feels kludgy.
Justin Dearing
It might feel kludgy, but the best design of the client-side of your app will be one that keeps the browser responsive. When you start long running processes you will hang the browser (big NO!) so it is best to spend the time designing how to manage async operations. Anyways .. have fun!
misteraidan
+2  A: 

You can also wrap you longterm function in a setTimeout(function(){longTerm();},1);