Search code examples
javascriptajaxbrowser-history

Clever way to manage browser history


I'm trying to implement a decent navigation in a AJAX application. What I am doing right now is the following:

  • Every time a user clicks an AJAX link, the corresponding call is performed and the hash is changed.
  • Whenever a new page is loaded, I check whether the hash is present and make the corresponding AJAX call to update the page. This ensures that bookmarks will work as expected.
  • Every 500ms I check if the hash is changed and perform the corresponding AJAX call. This takes care of users pressing the back/forward buttons, albeit with a sligth delay.

The third point is a bit annoying: I'd rather not have a timeout every 500ms just to check the hash, as most of the time it will stay the same.

Is there a better way to manage this? I cannot think of any alternatives, but maybe I am missing something.

Please, do not point me towards ready-made solutions, unless you know they are based on a different mechanism.


Solution

  • There is the "hashchange" event, which is to be implemented in HTML5. I'm not sure how good support is now... IE8 supports it, and I think Mozilla have their own implementation in a recent release. Other than that, there is nothing I'm afraid. Checking exery x ms is the way everyone does it.