Good Tutorial For Using Html5 History API (Pushstate)

Good tutorial for using HTML5 History API (Pushstate?)

For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.js provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).

You can read more about History.js here:
https://github.com/browserstate/history.js

For an article about Hashbangs VS Hashes VS HTML5 History API, see here:
https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling

HTML5 History API initial load issue

The issue is in this section of code.

$(window).on('popstate', function(e){
var state = e.originalEvent.state;
if(e.originalEvent && state){
loadContent(state);
}
});

If we check the MDN page on Window.onpopstate we find that the state event property is the state object passed into functions such as pushState.

the popstate event's state property contains a copy of the history entry's state object.

The means that the jQuery event object property e.originalEvent.state is the object you pass in on pushState. You could use this object for storing data, but your loadContent function expects a string for the URL, not an object.

I think you actually want to use document.location in your popstate handler.

$(window).on('popstate', function(e){
loadContent(document.location);
});

HTML5 history pushState is not working

Apparently one of the scripts I included had a declaration:

var history = ...;

Unbeknownst to me, all vars on the root actually live in the window scope so the custom history var actually overwrote the original window.history.



Related Topics



Leave a reply



Submit