2

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?

Matt Dunn
  • 5,106
  • 6
  • 31
  • 55
  • I don't understand why you use `pageshow`. Could you use `$(function()){}` – Marc Nov 19 '15 at 12:46
  • or `$( document ).ready()` – Marc Nov 19 '15 at 12:47
  • 1
    there seems to be an open bug: https://bugs.webkit.org/show_bug.cgi?id=156356 didn't find the workaround yet... – Georgii Ivankin Nov 14 '16 at 22:32
  • @GeorgiiIvankin did you find a workaround yet? Seems to be a bug on safari 10 (and recent IOS) – Erik Baan Feb 01 '17 at 11:48
  • @ErikBaan no, I didn't, unfortunately. – Georgii Ivankin Feb 01 '17 at 14:36
  • There is a bug in Safari as documented here: https://bugs.webkit.org/show_bug.cgi?id=156356 The Safari "pageshow" / "pagehide" events don't get fired more than once IF an iFrame is present on the page. In my case it's the Facebook "Like button" iFrame. Pretty annoying! – Bob Nov 19 '19 at 09:50

2 Answers2

1

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.

Matt Dunn
  • 5,106
  • 6
  • 31
  • 55
0

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

<body onunload=""></body>
Marc
  • 16,170
  • 20
  • 76
  • 119
  • Unfortunately this isn't a solution to this problem: $(document).ready() is only fired on initial DOM load; if the page is served from the BFCache, it does not fire. – Matt Dunn Nov 19 '15 at 12:56
  • Could you add an `onunload=""` attribute on your html body? – Marc Nov 19 '15 at 12:58
  • The `unload` handler apparently [doesn't necessarily fire in WebKit browsers](http://stackoverflow.com/a/6843651/301894), and I have found this experimentally also. – Matt Dunn Nov 19 '15 at 13:22