How do i force a html page to refresh?

How do i force a html page to refresh?

When you're developing applications like a blog or a page where the data may change based on user actions, you'll want that page to refresh frequently.

When the page refreshes or reloads, it will show any new data based off those user interactions. Good news – you can implement this type of functionality in JavaScript with a single line of code.

In this article, we will learn how to reload a webpage in JavaScript, as well as see some other situations where we might want to implement these reloads and how to do so.

How to Refresh a Page in JavaScript With location.reload()

You can use the location.reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button.

The reload() method is the main method responsible for page reloading. On the other hand, location is an interface that represents the actual location (URL) of the object it is linked to – in this case the URL of the page we want to reload. It can be accessed via either document.location or window.location.

The following is the syntax for reloading a page:

window.location.reload();

Note: When you read through some resources on “page reload in JavaScript”, you'll come across various explanations stating that the relaod method takes in boolean values as parameters and that the location.reload(true) helps force-reload so as to bypass its cache. But this isn't the case.

According to the MDN Documentation, a boolean parameter is not part of the current specification for location.reload() — and in fact has never been part of any specification for location.reload() ever published.

Browsers such as Firefox, on the other hand, support the use of a non-standard boolean parameter known as forceGet for location.reload(), which instructs Firefox to bypass its cache and force-reload the current document.

Aside from Firefox, any parameters you specify in a location.reload() call in other browsers will be ignored and have no effect.

How to Perform Page Reload/Refresh in JavaScript When a Button is Clicked

So far we have seen how reload works in JavaScript. Now let’s now see how you can implement this could when an event occurs or when an action like a button click occurs:


Note: This works similarly to when we use document.location.reload().

How to Refresh/Reload a Page Automatically in JavaScript

We can also allow a page refersh after a fixed time use the setTimeOut() method as seen below:

setTimeout(() => {
  document.location.reload();
}, 3000);

Using the code above our web page will reload every 3 seconds.

So far, we've seen how to use the reload method in our HTML file when we attach it to specific events, as well as in our JavaScript file.

How to Refresh/Reload a Page Using the History Function in JavaScript

The History function is another method for refreshing a page. The history function is used as usual to navigate back or forward by passing in either a positive or negative value.

For example, if we want to go back in time, we will use:

history.go(-1);

This will load the page and take us to the previous page we navigated to. But if we only want to refresh the current page, we can do so by not passing any parameters or by passing 0 (a neutral value):

history.go();
history.go(0);

Note: This also works the same way as we added the reload() method to the setTimeOut() method and the click event in HTML.

Wrapping Up

In this article, we learned how to refresh a page using JavaScript. We also clarified a common misconception that leads to people passing boolean parameters into the reload() method.

Thanks for reading!



Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How to force a page to reload from server at browser launch with JavaScript

I spent weeks finding a way to refresh a page or a tab from the server once a user starts or restarts the browser. I was very surprised to find nothing about this topic.

Let's dig into the context, tries and the solution I came up with.

Context

Typically, once a user opens a browser and gets to a page, it directly provides the page in cache without refreshing any data from the server. Obviously, this only applies if the user is not in a private navigation.

In this case, as a user, I always need to open the browser and then manually reload the page to get the last updated data. What? Am I too lazy? Sure I am a developer!

My goal was to detect when the browser launches and automatically refresh the page or the tab at this moment so end users do not need to manually reload the page and updated data immediately come to their eyes! Sounds nice!

Tries

As I am using a Service Worker that in my case handles expired pages and refreshing data (requesting data from the server if a page expired), I noticed the navigation through the browser was always in a back forward state when loading the page after browser launch and actually bypassed the Service Worker to return the page from cache. No way!

Here are the solutions I tried:

  • set Cache-Control header to no-cache, max-age=0, must-revalidate for all my pseudo-dynamic pages so it will force the browser to automatically refresh them. My Service Worker was in charge to set this header so my assets still were cached in my CDN. It was okay because my Service Worker was handling these pages based on an expiration date so they still were put in cache based on this date. But it did not work, once the browser launched and and I accessed the page, it still was outdated data loaded from cache;
  • detect when a tab becomes active to reload the page using tabs API but I found nothing really useful;
  • use localStorage API in combination with page Visibility API to store when users first loaded the page, detect when they left the page and reload it when the page becomes visible after a certain minimum amount of time (saying 10 minutes for an example). No way to make it worked at browser launch, it only automatically refreshed the page when the user was getting back to the tab passing 10 minutes (not so bad, but was not my use case).

I still was unable to detect browser launch in my JavaScript.

The solution

I finally came up with a solution using Performance and PerformanceNavigationTiming Level 2 APIs.

Experimental

PerformanceNavigationTiming Level 2 API is still at a Working Draft status which means this solution is using an experimental technology. Please use with caution.

Browser compatibility

Browser compatibility is not as bad as expected for an experimental feature. Only Safari, iOS Safari and IE are not supported the solution.

APIChromeEdgeFirefoxIEOperaSafariWebView AndroidChrome AndroidFirefox AndroidOpera AndroidiOS SafariSamsung Internet
Performance 6 12 7 9 15 8 <=37 18 7 14 9 1.0
Performance.getEntriesByType 28 12 35 10 15 11 <=37 28 35 15 11 1.5
PerformanceNavigationTiming 57 12 58 No 44 No 57 57 58 43 No 7.0
PerformanceNavigationTiming.type 57 12 58 No 44 No 57 57 58 43 No 7.0
PerformanceNavigationTiming.unloadEventStart 57 12 58 No 44 No 57 57 58 43 No 7.0

Code

if ('performance' in window) {
  const navigationLastEntry = performance.getEntriesByType('navigation').pop();

  if (navigationLastEntry
      && navigationLastEntry.type === 'back_forward'
      && navigationLastEntry.unloadEventStart === 0) {
    window.location.reload(true);
  }
}

Usage

This code does not need the DOM or the page to be loaded to be used. Actually it should be executed before these events are fired.

I typically put this code at the first lines of my index.js file, outside DOMContentLoaded event, but you could use it in the head section of your document. Personally speaking, it reloads really fast the page even though used in the index.js referenced at the end of my HTML files. Adapt to your need.

How it works

First the code checks Performance API is supported by the browser.

It then get the last navigation entry.

Finally it will reload the page only if:

  • there is a last navigation entry;
  • the type of navigation is back_forward;
  • the time immediately before the user agent starts the unload event of the previous document (unloadEventStart) equals 0 which means there is no previous document.

Please note that the navigation is through the browser's history traversal operation back_forward when:

  • users press Previous/Next buttons in the browser;
  • users press Previous/Next buttons on their keyboard;
  • users start or restart the browser and get to the page or tab.

These 3 conditions all put together allow us to detect when the browser loads the page or tab after and only after the browser has launched. Any other back_forward navigations won’t make the page to reload.

Finally calling window.location.reload() with true option indicates the page will reload from the server, false or no argument to reload from cache.

That’s it! At the end of the day that was a quite simple solution!

Discussion and Contribution

As I am more of a back-end developer, please let me know if something's wrong or feel free to contribute if you have an alternative or better solution.

Thanks,
Adrien

How do I trigger a refresh page?

You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.

How do I force cache refresh in HTML?

To ensure you see the latest version of a site you need to clear the cache memory. This is done by doing a force refresh by pressing both control and F5 buttons simultaneously on your keyboard (depending on your browser). Most times a simple force cache refresh won't work and you need to clear the cache by hand.

How do you refresh code in HTML?

In HTML and XHTML, one can use the meta element with the value of the http-equiv attribute set to " Refresh " and the value of the content attribute set to "0" (meaning zero seconds), followed by the URI that the browser should request.

How do I get my Web page to refresh automatically?

How to Automatically Reload a Web Page at a Certain Time.
Launch your browser..
Go to app/extension store (Chrome Web Store, Firefox Add-Ons, Microsoft Edge Add-ons Store, etc.)..
Enter “auto-refresh” in the search bar..
Choose an extension..
Follow the prompts to download and install the extension onto your browser toolbar..