How can I save history with AJAX just how github or google+ do. I use jQuery and I do not want to use some kind of hack like the # and #! tricks, because if I do, I'll need to change my whole project and make my life much more complicated?
3 Answers
Github and Google+ are using history.pushState
.
You can change the current url like this:
history.pushState(null, null, '/the-new-url');
This is supported by Firefox, Chrome, Opera, Safari; not IE.
There are basically two options when it comes to AJAX and history.
The # method (which isn't a hack btw). Since you don't want that one you only have option 2 left.
Use PushState. This is what Facebook, GitHub and a few others use. It's not supported by all browsers though and if you want complete cross-browser compatibility you will have to use a system which can degrade to option 1.
A very simple way to implement this is Backbone.js Router class.
-
5The # method is very much a hack. The point of fragment identifiers is to link to specific parts of a document, not to tell JavaScript which URLs to get data from to populate parts of the page via Ajax.– QuentinCommented Aug 24, 2011 at 11:50
-
1Well, yes, if we are really picky and strict, that was the original intended use, but since it's so widely supported and used, I would more like to call it a "clever use of mechanics" than a "hack" which I think sound way too negative.– Zeta TwoCommented Aug 24, 2011 at 11:56
-
1I think that 'hack' does not sound negative enough. In this context, the term means "Using something for other than its intended purpose", which fits this exactlyl– QuentinCommented Aug 24, 2011 at 11:58
There is a simple jQuery hashchange plugin that is designed to solve this specific problem.
I haven't used it; I don't know how it keeps track of the url history.