Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh page and run function after JavaScript

I'm trying to refresh a page and then run a function once the refresh has been completed. However the code I have now, runs the function and then it only refreshes it, meaning I lose what the function did. Is there a way to solve this?

My code

function reloadP(){
    document.location.reload();
    myFunction();
}

<button onclick: "reloadP()">Click</button>    
like image 988
Lost Soul Avatar asked Jan 28 '17 00:01

Lost Soul


People also ask

How do you call a function after a reload page?

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.

How do you refresh a page using JavaScript?

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 you reload a function?

The true keyword force to reload the page from the server, while the false keyword reloads the page from the cache. The false is the default parameter of this method, so if we omitted the parameter's value, the reload() method reloads the page from the cache. It means that the object. reload() is same as the object.

Can refresh the webpage in JavaScript by using?

Location. reload() method is used to refresh the webpage in javascript.


2 Answers

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

like image 199
Barmar Avatar answered Oct 18 '22 18:10

Barmar


function myFunction() {
    document.getElementById("welcome").textContent = "Welcome back!";
}

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

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

DEMO: https://jsfiddle.net/barmar/5sL3hd74/

like image 41
Félix Pujols Avatar answered Oct 18 '22 18:10

Félix Pujols