0

I have an intranet site (no Internet) built on HTML/CSS/JS where a bunch of info is displayed for employers. The data changes weekly. The intranet was built and elaborated on this: https://www.w3schools.com/howto/howto_js_vertical_tabs.asp The problem is that when users to the page they don't see updated info, as the browser loads from cache. After ctrl-f5 all good of course. However, I would like to solve this in a more systematic way.

I've read quite a few posts here and outside, but they don't work for me. For instance, I have this code in JS:

let reloaded = false;
const ctrlF5 = function(){
  const dateNow = parseInt(Date.now());
  const lastDateTime = localStorage.getItem('lastDatetime');
  if (dateNow > parseInt(lastDateTime) || lastDateTime === null) {
    if (!reloaded) {
    // Set the flag to true to prevent the page from being reloaded again
      reloaded = true;
      location.reload();
    }
  }
  localStorage.setItem('lastDatetime', parseInt(Date.now()));
}
window.onload = () => {
  ctrlF5();
}

The problem is that when the user clicks on the button, the page starts flickering rapidly until the stop button on the browser is pressed. Also the page never updates. The reason behind the onclick event listener on the button is because I'd like to refresh the related div only, but I haven't gotten that far yet, work in progress. If the function is run when the page loads the result is the same. If instead of location.reload(); I use window.location.href = window.location.href the result is the same. How to reload the page (not just refresh) using JS? Possibly no Jquery.

UPDATE: I notice that when the page flickers the value in the localStorage keeps changing/increasing, so it means that the page is being loaded continuously until user stops it. Why this happens I have no idea.

sigfried
  • 49
  • 1
  • 6
  • `lastDateTime` will likely be a string. If it's a unix timestamp, convert it using `new Date(lastDateTime)`? – evolutionxbox Dec 13 '22 at 14:26
  • `location.reload` [will not bypass the browser's cache](https://stackoverflow.com/questions/1011605/clear-the-cache-in-javascript). – Ben Aston Dec 13 '22 at 14:32
  • @evolutionxbox many thanks, that does not fix it but for sure it is a good point, I'll amend my code – sigfried Dec 13 '22 at 16:05
  • @BenAston thanks! If it does or not I can't even verify, as in my case it behaves weird. Plus it seems it is deprecated. Thanks for the links, I've tried few easy/quick suggestions in that link but no joy. However, I will follow the advice of creating js file versioning. It seems the most viable solution. If you make in "an answer" I'll flag it as a solution – sigfried Dec 13 '22 at 19:12

0 Answers0