Bibin
Bibin

Reputation: 434

HTML page unload is not getting called always in IE

I have an onunload method written on the body of a form. Since the page got large amount contents to be streamed from the server,it takes a while to download the entire form. While the form gets downloaded to the browser,if the user clicks the window close button, the unload event (written to call a server side action to reset some flag) is not getting triggered sometimes. The unload method is written towards the end of the page, is that a reason for this? Is there anyway by which we can make sure that onunload is guaranteed to be called?

Upvotes: 1

Views: 1870

Answers (3)

Georgii Ivankin
Georgii Ivankin

Reputation: 2712

The thing that hits you is probably the fact that IE doesn't fire an unload event if window.onload hasn't fired yet. The solution is described in this blog post: http://blog.moxiecode.com/2008/04/08/unload-event-never-fires-in-ie/

Upvotes: 1

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

IE has an onbeforeunload event, you can use that instead. Just set a flag so that your onunload can exit early if onbeforeunload already did its thing.

window.onunload = window.onbeforeunload = function () {
    if (window.isAlreadyUnloaded) return;
    window.isAlreadyUnloaded = true;
    // do your stuff here.
}

Upvotes: 0

DanRedux
DanRedux

Reputation: 9349

There are two reasons. One, like you said, the browser may not even be reaching the unload, so you should declare it above your body tag.

The other is that, as GoldenNewby already stated, you need to give the code some time to finish, such as an alert. This is because the JavaScript is cleared from memory the moment the next page is ready, and execution is simply stopped on the old script. If you can guarantee the script will take less time than a page load, you won't need an alert, but if it could take more than 2ms or so to execute, you will need to buy some time.

Upvotes: 0

Related Questions