views:

33

answers:

2

Hi all,

I have heard in the past unload, or onunload, is not always called. However, I would like to know how often it is not called. What conditions lead to it not being called? Is this different for Firefox and IE?

Thanks, Grae

A: 

I'm pretty sure the unload event always fires during a normal page exit, but it does go by two different names... onunload is used by IE (& understood by Opera) while unload is used by the other browsers.

It's not supposed to be cancel-able for security reasons (one of the purposes was in eCommerce to perform logout & cleanup). That being said a hardware reset (reset, power off, power cut) or process kill probably prevents it.

There are differences in scope when the event happens - in IE you'll find a fair bit of code has been pushed out of scope (to the point that trying to call a library function may fail complaining it doesn't understand {because it's now out of scope}). FF, Chrome & Opera seem to keep most things around during this event.

Rudu
That was not more understanding. I heard it never got run if the page was not loaded fully. Like the user clicks close when the page is half loaded.
Grae
+2  A: 

I did some testing a while ago. I used two techniques:

$(window).unload( fn ); // jQuery method  

window.onbeforeunload = fn; // by Microsoft, but implemented in most browsers

You can view my test results here: http://vidasp.net/jQuery-unload.html
(To sum them up: window.onbeforeunload has complete support in all popular browsers except Opera)

Šime Vidas
Thanks, it looks like you went to a lot of work.
Grae
How come you used onbeforeonload rather than onunload?
Grae
@Grea I actually cannot remember why I did that. But there must have been some valid reason. Maybe I figured that `onbeforeunload` has greater support than `onunload` so I just went with it...
Šime Vidas