Prevent Safari from caching the page when clicking the back button
P粉295728625
P粉295728625 2024-01-21 15:00:44
0
2
410

Safari has issues loading old You Tube videos when clicking the back button. I tried adding onunload="" (mentioned here Preventing cache on back-button in Safari 5) to the body tag but it doesn't work in this case.

Is there any way to prevent safari from loading from cache on a page?

P粉295728625
P粉295728625

reply all(2)
P粉514001887

All these answers are a bit hacky. In modern browsers (Safari), only works on onpageshow solution,

window.onpageshow = function (event) {
    if (event.persisted) {
        window.location.reload();
    }
};

But on slow devices, sometimes you will see the cached view from a split second before reloading. The correct way to handle this is to set the Cache-Control correctly on the server response, as shown below

'Cache Control', 'No cache, max-age=0, must be re-validated, no storage'

P粉495955986

Your problem is caused by back cache. It should save the complete state of the page when the user navigates away. When the user navigates back using the back button, the page can be loaded from cache very quickly. This is different from normal caching which only caches HTML code.

When bfcache loads the page, the onload event will not be triggered. Instead, you can check the persisted property of the onpageshow event. It is set to false on initial page load. It is set to true when the page is loaded from bfcache.

Kludgish's solution is to force a reload when the page is loaded from bfcache.

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload() 
    }
};

If you are using jQuery, do the following:

$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload() 
    }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template