The Problem
Last blog, I redesigned the standard ajax library to allow for simultaneous open connections. This time, I tackled something a little more navigation bound.
Ajax is an amazing little compilation of code that has the capability of reloading only parts of a page that have changed.
source: Ajax, Rewritten!, 11/04/2009
Keep that quote in mind for a moment, while I explain some behavioral methods in web browsing.
Let’s say that you are on an office supply site with a few links you are interested in: “View Cart” and “Checkout”. You can’t remember what is in your cart, so you click the view cart link. While the page is loading, you remember what you had and change your mind, so you then click the checkout link. Your browser directs the page to the checkout link. Why? Whenever you click a link that tells your browser to load a page, it ignores all previous link clicks.
Now let’s get to the behavior of Ajax. Ajax by nature does not tell the browser to load a new page, it only reloads parts of it. The side effect is that if you are on an Ajax powered website, behavior is different. Let’s say you click on a link to Google from the Ajax page, and then change your mind and then click on the page’s home link. What happens? Because there is only one real page request (to Google) it will continue loading Google’s page.
The Fix
Using the JavaScript event object window.onbeforeunload, we can tell the ajax library that we are in the middle of leaving the page (clicking a link to another page). We can then tell each page request sent through ajax library to check if we are in the middle of leaving the current page. If we are, a stop command is issued to the browser (IE plays differently, so some creative code was required). We don’t have to go back and tell the library that the page is no longer in the middle of leaving, because leaving the page will unload the page’s variables by default.
The Effect
With the changes to the library in place, things function as they should. If we click a link to this blog, and then change our mind and click on the ajax powered home page, the original link request is halted. Hurray coding!