Home  >  Q&A  >  body text

Prevent Safari from caching the page when clicking the back button

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粉295728625P粉295728625271 days ago385

reply all(2)I'll reply

  • P粉514001887

    P粉5140018872024-01-22 13:43:52

    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'

    reply
    0
  • P粉495955986

    P粉4959559862024-01-22 09:58:12

    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() 
        }
    });

    reply
    0
  • Cancelreply