Can the unload Event be Used to Reliably fire ajax Request?

This method is fairly reliable, if your server is fast enough to respond. Something to really watch out for though. If you close the browser and send AJAX request on unload event, there’s a very good chance that the response isn’t going to come back from the server in time before the window object is destroyed. What happens in this case (at least with IE) is that it will orphan your connection object and not terminate it correctly until the connection timeout is hit. If your server doesn’t have connection keep-alive turned on, after you close 2 windows (while still having another window open), you will run out of open connections to the server (for IE6-7, for IE8 – 6 windows) and you will not be able to open your website until your connection timeout is hit.

I ran into a situation like that before were I was opening a popup window that was sending an AJAX request on unload, it was very reliable, but it was plagued by the issued described above, and it took really long time for me to track it down and understand what’s going on. After that, what I did, is I made sure that opening window would have the same code to call server, and on every unload checked for the opener and ran the code there if it was present.

It seems that if you close the very last browser window, IE will destroy connection properly, but if one other window is open, it will not.

P.S. And just to comment on the answer above, AJAX is not really async. At least JS implementation of it isn’t. After you send a request, you JS code is still going to be waiting for response from the server. It’s not going to block your code execution, but since the server might take a while to response (or long enough for Windows to terminate IE window object) you might and probably will run into the problem described above.

Leave a Comment