1

I want to clear cache and hard reload browser but how to do that using JS/jQuery command when the document is ready?

My reference:

  1. 1st Link
  2. 2nd Link
  3. 3rd Link

I have tried below but not working except commented with this one but it continuously reload with never stop. Why this happen? How to make it just reload 1 time only.

$(document).ready(function(){
    // window.location.reload(false);
    // document.location.reload(true);
    // window.location.reload(true);
    // window.location.href = window.location.href;
    // location.reload(true); //this one
});

Updated: Googling and tried this but not working.

sessionStorage.setItem("origin", window.location.href);

$(document).ready(function(){
    if(window.location.href == sessionStorage.getItem("origin")){
        window.location.reload();
        sessionStorage.removeItem('origin');
    }
});
mastersuse
  • 936
  • 1
  • 15
  • 35
  • 3
    to make it reload one time only, you'd have to store some information saying that you've reloaded before. So, perhaps before you call `location.reload`, you could set some variable in SessionStorage, and then check if that is set and only reload if it's not set – TKoL Jan 04 '21 at 10:31
  • hi, i am so sorry and no idea how to do that. – mastersuse Jan 04 '21 at 10:36
  • just google `sessionStorage`, it's pretty easy to deal with – TKoL Jan 04 '21 at 10:56
  • Actually, another option is to look at the `document.referrer` attribute -- if it's equal to `location.href`, don't reload, otherwise do reload – TKoL Jan 04 '21 at 10:59
  • This is because, when you reload, the referrer is equal to the current href (not sure if you'll need to consider query parameters at all, but generally this will work) – TKoL Jan 04 '21 at 11:00
  • i have google and tried updated posting above but not working. – mastersuse Jan 04 '21 at 11:18
  • Have a look at my answer below. – Shahnawaz Hossan Jan 04 '21 at 11:18
  • Don't try to do this with JS. Set proper cache control headers on your HTTP resources in the first place. – Quentin Jan 04 '21 at 11:19

1 Answers1

1

You can set a localStorage for that, simply check whether your localStorage has a value or not. If not, reload first and then set a value. Have a look at the example below:

$(document).ready(function () {

    var reload = localStorage.getItem('reload');

    console.log(reload);

    if (reload === null) {
        location.reload(true);
        localStorage.setItem('reload', "stop");
    }

});
Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24