What are the differences between history.pushState & location.hash?
location.hash
has a better support than the history.pushState
method.
The advantage of the pushState
method is that you can bind a state to the history entry.
If you don't need this state object, I recommend to use the location.hash
property, to have better compatibility with older browsers.
location.hash = 'new-hash';console.log(history.state); // null or undefinedhistory.pushState({extraData: "some state info"}, '', 'new-hash'); //<---console.log(history.state); // [object Object] = {"extraData": "some state info"}
Pushstate is the future. It's better because:
- It looks cleaner.
- On revisit of a deep link you can actually surface real serverside data to support things like SEO and Facebook Open Graph (both send spiders to scrape the html of your page).
- Servers don't have access to hash tags data so you don't see it in your server logs so it helps some with analytics.
- It helps fix hash tag issues. For example I had an Nginx rewrite to redirect users visiting my app to the same https url. It works in all browsers but Safari which will redirect you to just the domain without the hash (so annoying)!
- You can actually use hash tag for what is was meant for, deep linking to sections of long pages.
- You can fallback to using real HTTP backend requests for browser that don't support push state OR you can fallback to using hash tag. Both require extra implementation but are easily doable with a little work.
See this talk from Github designer for more: http://warpspire.com/talks/responsive/
history.pushState
is better than location.hash
. but it is a HTML5 feature. so always better to have a fallback method like below.
if (typeof(window.history.pushState) == 'function') { window.history.pushState(null, path, path);} else { window.location.hash = '#!' + path;}