Refresh page and run function after JavaScript

2019-02-25 10:50发布

Hello I am trying to refresh my page and then run a function once the refresh has been completed. However the code I have now runs the funxtion then it only refreshes meaning I lose what the function does. Is there a way to solve it?

My code is:

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

<button onclick: "reloadP()">Click</button>    

1条回答
Fickle 薄情
2楼-- · 2019-02-25 11:14

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

查看更多
登录 后发表回答