繁体   English   中英

页面加载时HTML5 onpopstate

[英]HTML5 onpopstate on page load

我正在使用新的HTML5 onpopstate事件。 使用Firefox 4,在页面加载时触发window.onpopstate事件,而在Webkit中似乎并非如此。

哪种行为正确?

在导航到会话历史记录条目时,在某些情况下会触发popstate事件。

http://www.whatwg.org/specs/web-apps/current-work/#event-popstate

从我的理解,虽然我可能是错的,看到加载页面确实意味着历史记录被创建并遍历,是的,它应该在页面加载时触发。

另见,

http://www.mail-archive.com/whatwg@lists.whatwg.org/msg19722.html

和,

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

在页面加载时启动onpopstate是正确的,WebKit很快就会出现这种情况。 WebKit 534.7(Chrome 7.0517.44)现在就是这样的。

我在其上提交了一个Chrome错误,但事实证明这是理想的行为; 需要它才能正确处理某些后退/前进按钮操作。 有关更多讨论和链接,请参阅code.google.com上的此错误报告

我仍在尝试为onpopstate事件处理程序提供一个好的代码模式。

我不知道这是不是你问的问题,但是我对一个仅限ajax的 onpopstate事件处理程序的解决方案是将window.onload refreshed的变量设置为true ,并在history.pushState调用时将其设置为false ; 然后在onpopstate处理程序上只做refreshed东西是false

看起来很傻,但确实如此,但我无法做得更好。

刚刚解决了这个问题,修复实际上非常简单。 Firefox在初始页面加载时不会触发onpopstate。 触发一个popstate后,返回false或阻止page.load动作的默认值,你就是金色的。

干杯。

在这里采取行动:www.thecoffeeshopnyc.com

// Write in a new handler for Firefox, which does not fire popstate on load.
// Modern Webkit browsers fire popstate on load. The event handler below fires the controller
$(window).load(function () {
    if ($.browser.mozilla) {
        // Your func.
    }
})

// Add the event listener. If the above is false, it will still run as intended in normal browsers.
window.onpopstate = function() {
    // Your func.
}

浏览器倾向于在页面加载时以不同方式处理popstate事件。 Chrome和Safari总是在页面加载时发出popstate事件,但Firefox不会。

该引用来自Mozilla的文档: https//developer.mozilla.org/en-US/docs/DOM/window.onpopstate

我倾向于同意Mozilla系统。 页面加载不是需要触发额外popstate事件的操作,因为状态未被弹出,它是第一次加载。

我猜测Webkit是为了方便而做的...在我的所有实现中,在初始popstate被触发之前,延迟加载我的处理程序一直是一个不便。

而不是这个(使用伪函数):

AddEventHandler(window, 'popstate', OnPopState);

我必须做这样的事情:

AddLoadEvent(window.setTimeout(function() 
    { 
        AddEventHandler(window, 'popstate', OnPopState); 
    },0));

如果有人感兴趣,我已经想出了一个合适的模式来处理onpopstate (这段代码假设jQuery,为了清晰起见,特征检测检查被剥离):

$(function() {

  // 1. Add initial state to current history record on page load.
  var href = location.href;
  history.replaceState({"href": href}, null, href);

  // 2. Now attach the popstate handler.
  window.onpopstate = function(ev) {

    // Raised on page load this event will still contain no state.
    var state = ev.state;
    if (state && state.href) {

      // 3. Add your logic, use `state` and `state.href` as you see fit.          

    }
  };

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM