pageshow event on Safari

2.8k Views Asked by At

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

There are 2 best solutions below

1
Matt Dunn On BEST ANSWER

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
Marc On

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

<body onunload=""></body>