Issue:
-
Attach a click event on a link on a page (say link to http://google.com/)
-
Try doing an AJAX or getJSON (JQuery specific call) from the function bound to that click event
-
The AJAX or getJSON call is never completed (even if we add an explicit half-second pause)
Sample HTML page: http://paraschopra.com/temp/bah.html
Sample Server logger (to check counts): http://paraschopra.com/temp/count.txt
The bah.html file contacts a simple PHP logger via getJSON if you click on ABC link. The logger increments the number in count.txt. You will realize on Chrome 6 (and Safari), the server never gets contacted while on FF, IE, Chrome 5 the server gets contacted. Is it a bug or what? Is there a workaround right now?
By the way, works on all other browsers: FF, IE, etc.
It’s a bug — but not in the new browsers. 🙂 What you’re doing is setting up an asynchronous Ajax call, after which the page is being torn down because a link has been clicked that takes you to a new page. Your call never completes because the page is gone.
You can’t reliably start asynchronous Ajax calls when the page is being torn down (well, you can reliably start them, but not have them reliably complete). Your only real options as far as I know are:
Make the Ajax call synchronous (blech). This makes for a noticeable delay for the user.
Cancel the link’s default action and then change the window location yourself when the call completes (blech). Still a noticeable delay for the user AND it interferes with “open in new window”, “open in new tab”, etc.
Approach the entire problem differently. The usual way is to have the link go to a page which then redirects to the actual target location. (That’s what Google does, for instance, in Google Groups and various other places.) This is what I’d do for a general web-facing page (intranet apps are different), not least because it’s totally reliable and works even if the user has JavaScript disabled in their browser.
You’ll find a lot of questions and answers on this topic here on StackOverflow if you search for questions about doing things during the
unloadandbeforeunloadevents.I wouldn’t be entirely surprised to find out there was a way to bring web workers to bear on this problem, but I expect many of the trade-offs would be the same, and web workers are only supported by a small number of browsers at present (including Chrome).