window bind POPSTATE

前端 未结 8 1981
一整个雨季
一整个雨季 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 21:51

    There was a bug in Webkit that incorrectly implemented the "popstate" event. Check out this simple post explaining the problem (cool little show and tell): http://www.bcherry.net/playground/pushstate

    My suggestion would be to implement your own "popstate" event tracker for Safari. Something like this:

    $(window).load(function(){
      function fire_popstate(){
        $(this).trigger("popstate"); // fire it when the page first loads
      }
      var lasthash = window.location.hash;
      setInterval(function(){
        var currenthash = window.location.hash;
        if(lasthash != currenthash){
          fire_popstate();
        }
      }, 500);//check every half second if the url has changed
    });
    

    You could wrap that statement in a browser test to check for safari. Even better see if "popstate" has been fired by the time the DOM is ready and then apply the inner function to replace the implementation. The one thing you don't want to happen is have two popstate events to be fired (duplicating your event handler logic, great way to lock up the UI).

提交回复
热议问题