window bind POPSTATE

AnApprentice picture AnApprentice · Jan 14, 2011 · Viewed 38.4k times · Source

Given the following:

$(window).bind("popstate", function() {
    alert('popstate');
});

On first load, the alert fires with FireFox and Chrome but not Safari. Why is that? Anyone else seen this and know how to best solve for this?

Answer

Nobu picture Nobu · May 11, 2011

See the code from pjax. pjax is fairly popular open source library now, so the below logic might be the best to avoid this issue.

var popped = ('state' in window.history), initialURL = location.href
$(window).bind('popstate', function(event) {
  // Ignore inital popstate that some browsers fire on page load
  var initialPop = !popped && location.href == initialURL
  popped = true
  if ( initialPop ) return
  ...

https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js