What are the differences between history.pushState & location.hash? What are the differences between history.pushState & location.hash? javascript javascript

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:

  1. It looks cleaner.
  2. 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).
  3. 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.
  4. 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)!
  5. You can actually use hash tag for what is was meant for, deep linking to sections of long pages.
  6. 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;}