【问题标题】:Prevent page reloading continuously防止页面不断重新加载
【发布时间】:2015-06-03 03:09:58
【问题描述】:

我在函数中使用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);被触发时才停止不断的重新加载并刷新页面呢?

【问题讨论】:

    标签: javascript jquery


    【解决方案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. 它在重复

    更新: 请阅读有关操纵浏览器历史记录的文档。 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 事件。它用于其他目的。

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

    【讨论】:

    • 谢谢。你是说pushState触发时我不能刷新页面?
    • @Becky 不。我是说您无法在 popstate 事件中重新加载页面,因为它发生在 Chrome 和 Safari 的页面加载时。 yoru 代码的第一部分一切正常。
    • 有哪些选项可以替代popState
    • @Becky 实际上,我不明白你为什么要在popstate 上重新加载页面。 “能够在 $('#go_btn') 按钮触发 newurl 时刷新页面”。如上所述,history.pushState()history.replaceState() 触发 onpopstate 事件。使用它的原因是什么?有没有刷新的必要?如果你想用新的 url “重新加载”一个页面,那么你不需要它。 history.pushState()history.replaceState() 旨在替换浏览器历史记录中的 URL,而不是加载新页面!
    • 是的,当$('#go_btn')被点击且IF语句为真时,有理由重新加载页面。
    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2018-01-13
    • 2015-06-17
    • 2011-12-14
    相关资源
    最近更新 更多