Refresh a Page Using JavaScript or Html

How do I refresh a page using JavaScript?

Use location.reload().

For example, to reload whenever an element with id="something" is clicked:

$('#something').click(function() {
location.reload();
});

The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false, so by default the page may reload from the browser's cache.

Refresh page and run function after - JavaScript

You need to call myFunction() when the page is loaded.

window.onload = myFunction;

If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.

window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}

function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}

DEMO

Auto refresh page every 30 seconds

There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta tag in your head tag.

<meta http-equiv="refresh" content="30">

The browser will then refresh the page every 30 seconds.

If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with Location.reload() (docs) inside a setTimeout():

window.setTimeout( function() {
window.location.reload();
}, 30000);

If you don't need to refresh the whole page but only a part of it, I guess an AJAX call would be the most efficient way.

i want to refresh my page 5 times on one click

You can add query string parameter refreshesLeft and on button click redirect to mypage?refreshesLeft=5. Add onLoad handler to check if you have query string parameter set, and if yes, decrement it and redirect.

<button type="button" onClick="Refresh()">Close</button>

<script>

function Refresh(refreshesLeft) {
refreshesLeft = refreshesLeft || 5;
window.parent.location = window.parent.location.href + '?refreshesLeft='+refreshesLeft;
}

function onLoad() {
let params = new URLSearchParams(document.location.search.substring(1));
let rl = params.get("refreshesLeft")
if (rl) Refresh( (rl | 0 ) -1)
}

document.addEventListener("DOMContentLoaded", onLoad)

</script>

Saving state of html page on page refresh

You have to take advantage of browser's History API. On each content load, you have to push state to the history.

On hard refresh, you have to parse the url and fetch the correct content.

One thing to keep in mind with this approach is that you have to jump through hoops to make it easy for search engine crawlers to index all your "pages".

Another approach is to use Turbolinks.

Cheers.



Related Topics



Leave a reply



Submit