javascript 页面刷新函数的回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16926600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:28:45  来源:igfitidea点击:

A callback for a page refresh function

javascriptjquery

提问by Tommy Naidich

Is there any way to implement a callback for a page refresh function, check if the page is ready after it is refreshed and then print a message? I'd like to show refresh the page and show a certain message after clicking a button, however, I need to stay within my code in order to know what message to show. Anything similar to the next code would be great:

有什么办法可以实现页面刷新功能的回调,刷新后检查页面是否准备好,然后打印信息?我想在单击按钮后显示刷新页面并显示特定消息,但是,我需要留在我的代码中才能知道要显示什么消息。任何类似于下一个代码的东西都会很棒:

location.reload(function(){
   alert ('done refreshing and document is ready');
});

回答by xbonez

On page reload, your JS application gets re-initialized and starts all over again, so you cannot have a callback.

在页面重新加载时,您的 JS 应用程序会重新初始化并重新开始,因此您不能有回调。

However, what you can do is add a hash fragment to the URL before reloading.

但是,您可以做的是在重新加载之前向 URL 添加一个哈希片段。

window.location = window.location.href + "#refresh";
window.location.reload();

Then, on page load, check if the hash fragment exists. If it does, you'll know you just refreshed the page.

然后,在页面加载时,检查哈希片段是否存在。如果是这样,您就会知道您刚刚刷新了页面。

回答by Marcelo Pascual

The way to go is using

要走的路是使用

$(document).ready(function(){
    alert('done refreshing and document is ready');
});

But it doesn't differentiate a first load from a refresh. But you could achive that using sessions. For example, using PHP:

但它不会区分第一次加载和刷新。但是您可以使用会话来实现。例如,使用 PHP:

<?php

session_start();

$showJs = false;

if( !isset($_SESSION['loaded_before']) ) {
    $showJs = true;
    $_SESSION['loaded_before'] = true;
}

?>
...
<?php if($showjs) { ?>
<script type="text/javascript">

    $(document).ready(function(){
        alert('done refreshing and document is ready');
    });

</script>
<?php } ?>

回答by Lucian Minea

If you really want to go javascript side, you can use sessionStorage.varName before reloading, and then you check that var and continue.

如果你真的想要去 javascript 方面,你可以在重新加载之前使用 sessionStorage.varName,然后你检查那个 var 并继续。