防止页面不断重新加载

Prevent page reloading continuously

本文关键字:新加载 加载      更新时间:2023-09-26

我在函数内使用window.history.pushState({)。这工作正常,如预期的那样。下面是一个例子:

$('#go_btn').click(function(){
   if ($('.green')) {
        var newurl = "cutomurl.html";
        if(newurl!=window.location){
             window.history.pushState({path:newurl},'',newurl);
        }
        return false;
   }
});

,我也得到了下面的代码,能够刷新页面时,newurl是由$('#go_btn')按钮触发。

$(window).on('popstate', function(){ 
    location.reload(true); 
});

在桌面版本上我似乎没有任何问题。但当我试图在iPad上加载这个页面时,它会不断地重新加载这个页面。那么,如何停止连续重新加载并仅在触发window.history.pushState({path:newurl},'',newurl);时刷新页面呢?

注意,仅仅调用history.pushState()或history.replaceState()不会触发popstate事件。只是触发popstate事件通过执行浏览器操作,例如单击后退按钮(或返回)在JavaScript中调用history.back()。事件只会被触发当用户在同一条目的两个历史条目之间导航时文档。

浏览器倾向于在页面加载时以不同的方式处理popstate事件。Chrome (v34之前)和Safari总是在页面上发出popstate事件.
根据mozilla Developer Network
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate

Safari总是在页面加载时发出popstate事件。这意味着

  1. 您的页面加载
  2. Popstate事件发生
  3. location.reload()执行
  4. 正在重复

:请阅读有关操作浏览器历史记录的文档。https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

看起来你误解了一些功能。

有一个#go_btn按钮。当你点击它时,你想要一个页面:

1。重载

使用location.reload()

if (newurl != window.location)
{
    // window.history.pushState({path:newurl},'',newurl);
    location.reload(true);
}

2。导航到新的URL

使用location.href将在当前窗口中打开新页面

if (newurl != window.location)
{
    // window.history.pushState({path:newurl},'',newurl);
    location.href = newurl;
}

3。不用做任何事情就可以改变浏览器历史记录和地址栏中的URL

使用window.history.pushState()window.history.replaceState()。它不会打开或重新加载新页面。它只在你不打算导航,但希望用户获得新的URL(方便浏览,历史或收藏)时使用。

if (newurl!=window.location)
{
    window.history.pushState({path:newurl},'',newurl);
}

在所有这三种情况下,您都不需要popstate事件。它被用于其他目的。

你需要哪一个?这取决于你的任务。
无论如何,将它们中的任何两个一起使用都不是不合逻辑和无用的。如果要刷新页面,推送历史状态的原因是什么?然后导航到它