Search code examples
javascriptreload

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>    

Solution

  • 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