HTML5 onpopstate on page load

前端 未结 6 1795
一整个雨季
一整个雨季 2020-12-06 06:18

I\'m using the new HTML5 onpopstate event. Using Firefox 4 the window.onpopstate event is triggered on a page load whilst in Webkit this does not seem to be the case.

<
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 07:05

    In case someone is interested, I've came up with a decent pattern for working with onpopstate (this code assumes jQuery, feature detection checks are stripped for clarity):

    $(function() {
    
      // 1. Add initial state to current history record on page load.
      var href = location.href;
      history.replaceState({"href": href}, null, href);
    
      // 2. Now attach the popstate handler.
      window.onpopstate = function(ev) {
    
        // Raised on page load this event will still contain no state.
        var state = ev.state;
        if (state && state.href) {
    
          // 3. Add your logic, use `state` and `state.href` as you see fit.          
    
        }
      };
    
    });
    

提交回复
热议问题