防止页面不断重新加载

时间:2015-06-03 03:09:59

标签: javascript jquery

我在函数中使用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);时刷新页面?

1 个答案:

答案 0 :(得分:1)

  

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

     

浏览器倾向于在页面加载时以不同方式处理popstate事件。    Chrome(v34之前)和Safari始终在页面上发出popstate事件   加载,但Firefox没有   根据Mozzila开发者网络
   https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate

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

  1. 您的页面加载
  2. 发生Popstate事件
  3. location.reload()执行
  4. 正在重复
  5. <强>更新: 请阅读有关操纵浏览器历史记录的文档。 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。导航到新网址

    使用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事件。它用于其他目的。

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

相关问题