pageshow event on Safari

2019-02-15 23:03发布

I have the following simple JavaScript, which I require in order to re-initialise some variables on page reload, specifically when the page is served from the Safari BFCache:

jQuery(window).bind('pageshow', function(event) {
    // I could inspect event.originalEvent.persisted here to check for BFCache hits,
    // but it isn't required in this instance.

    // Do some initialisation here
});

Let's say the user follows the below path, navigating to pages B and C, browsing back (i.e. using the back button) to page A after each:

A -> B -> A -> C -> A

The pageshow handler only fires for the first and second visits to A, i.e. the initial page load and the first BFCache load. So in essence, it seems pages served from the BFCache fire pageshow once and only once.

Is this the expected behaviour on Safari, and is there a way around it?

2条回答
贼婆χ
2楼-- · 2019-02-15 23:46

I appeared to have solved the issue by instead binding to the popstate event:

jQuery(window).bind('popstate', function(event) {
    // Do some initialisation here
});

which fires whenever the active history entry changes. This appears to fire consistently rather than just once, so achieves the goal of performing re-initialisation whenever a user lands on page, regardless of the mechanism for getting there.

查看更多
爷的心禁止访问
3楼-- · 2019-02-15 23:53

To disable the BFCache, you could add an onunload="" attribute on your html body.

<body onunload=""></body>
查看更多
登录 后发表回答