Mert Kadir Gursoy
2 min readMar 30, 2020

--

How to refresh a page only once with Javascript?

To begin with, to reload a page, there is a method that is window.location.reload();

However, to refresh / reload the page once, it is not useful stand alone.

Because when this method is triggered, the page is reloaded repeatedly.

Another solution to handle this issue is using Location hash Property.

Also there is a topic in stackoverflow that related with this issue which is One time page refresh after first page load.

So if we want to reload the page once without change the url (hash change), how can we do that?

For almost two months I researched then figured out how to do that by using “performance.timing.domLoading” timestamp of the browser ( when the page is loaded ) in a function and created a function reloadPage(); to reload the page once without change the url.

It works fine on the client-side Javascript project.

Here below the all steps of the function reloadPage();

function reloadPage() {
// The last "domLoading" Time //
var currentDocumentTimestamp =
new Date(performance.timing.domLoading).getTime();
// Current Time //
var now = Date.now();
// Ten Seconds //
var tenSec = 10 * 1000;
// Plus Ten Seconds //
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
location.reload();
} else {}
}
reloadPage();
  • 1. Getting the domloading time of the browser
  • 2. Getting the current timestamp
  • 3. The domloading time + 10 seconds (Unix Time Stamp)
  • 4. If current timestamp is bigger than the domloading time + 10 seconds (Unix Time Stamp) that means the page has not been loaded in last ten seconds. Therefore, the page is able to be refreshed via “location.reload();” method.
  • 5. Else, if current time is not bigger than the domloading time + 10 seconds that means the page has just been reloaded. Thus, It will not be reloaded repeatedly.

Finally, if you call the “reloadPage();” function in your Javascript file, it will only reload the page once.

--

--

Mert Kadir Gursoy

Product Team Lead | Product Management ~ Product Design ~ UX Research ~ Technical Project Management