小编典典

onpopstate处理程序-Ajax后退按钮

ajax

我正在使用pushState为网站上的Ajax内容创建有意义的URL。我想在用户单击前进或后退按钮时刷新Ajax内容。但是我遇到了问题,因为Chrome(正确)在“历史记录遍历”(前进/后退按钮)和“结束”(页面加载)上都暗示了onpopstate。我想创建一个区分页面加载和历史遍历的onpopstate处理程序,因为如果已经成功加载Ajax内容,我就不希望刷新它。有人可以帮助我区分两者吗?

window.onpopstate = function (event) {
    // If : Forward/back button pressed
        // Reload any ajax content with new variables
    // Else : Page load complete
        // Do nothing - content already loaded and correct
}

有关chrome和onpopstate的详细信息,请参见http://code.google.com/p/chromium/issues/detail?id=63040

谢谢


阅读 214

收藏
2020-07-26

共1个答案

小编典典

One way would be to initialize a variable to false on page load, and then on
your popstate event, check that variable. If it’s still false, set it to true
and do nothing. From then on all of your other popstate events should be only
from back/forward events.

var loaded = false;

window.onpopstate = function(e) {
    if (!loaded) {
        loaded = true;
        return;
    } else {
        // run your stuff...
    }
}
2020-07-26