Refresh page and run function after JavaScript

前端 未结 2 554
遥遥无期
遥遥无期 2020-12-16 16:46

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 meanin

相关标签:
2条回答
  • 2020-12-16 17:20
    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/

    0 讨论(0)
  • 2020-12-16 17:36

    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

    0 讨论(0)
提交回复
热议问题