window bind POPSTATE

前端 未结 8 2001
一整个雨季
一整个雨季 2020-12-07 21:25

Given the following:

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

On first load, the alert fires with FireFox and

8条回答
  •  被撕碎了的回忆
    2020-12-07 22:11

    An easy way to avoid this issue is to set the first argument on pushState to true then check against onpopstate. Similar to the pjax example but a bit more straightforward. The below example will run doSomething() for every popstate event except for the first page load.

    function setupPopState() {
      if (history.popState) {
        # immediately replace state to ensure popstate works for inital page
        history.replaceState(true, null, window.location.pathname);
    
        $(window).bind('popstate', function(event) {
          if (event.originalEvent.state) {
            doSomething();
          }
        });
      }
    }
    

提交回复
热议问题