加载页面时的window.onpopstate [英] window.onpopstate on page load

查看:818
本文介绍了加载页面时的window.onpopstate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩 window.onpopstate ,并且有一件事情让我有点懊恼:



< blockquote>

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


< a href =https://developer.mozilla.org/en-US/docs/DOM/window.onpopstate =noreferrer> source



我测试了它,并且在Chrome和Safari 5.1 +中,popstate事件在页面加载时触发,但不在Firefox或IE10中触发。 问题是,我只想听取 popstate 事件,其中用户点击了转发按钮(或者历史记录已更改通过javascript),但不想在pageload上做任何事情。



换句话说,我想区分 popstate 来自页面加载的事件来自其他 popstate 事件。



这是什么

  $(function(){
console.log() 'document ready');

setTimeout(function(){
window.onpopstate = func (事件){
//在这里做某事
},10);
});

基本上我尝试绑定我的监听器函数到 popstate 迟到,不能在页面加载时绑定,只能在以后。



这似乎有效,但是,我不喜欢这个解决方案。我的意思是,我怎么能确定为setTimeout选择的 timeout 足够大,但不是太大(因为我不希望它太多)等待。



我希望有一个更聪明的解决方案!

解决方案 检查 event.state in popstate 事件处理程序:

  window.addEventListener('popstate',function(event){
if(event.state){
alert('!');
}
},假);

为确保这项工作可行,始终指定一个非<$ c当调用 history.pushState() history.replaceState() null C>。另外,请考虑使用像 History.js 这样的包装库,以便在浏览器中提供一致的行为。


I'm playing with window.onpopstate, and there is a thing that annoys me a little bit:

Browsers tend to handle the popstate event differently on page load. Chrome and Safari always emit a popstate event on page load, but Firefox doesn't.

source

I tested it, and yeah, in Chrome and Safari 5.1+ the popstate event is fired on page load, but not in Firefox or IE10.

The problem is, that I want to listen only to popstate events where user clicked the back or forward button (or the history was changed via javascript), but don't want to do anything on pageload.

By other words I want to differentiate the popstate event from page load from the other popstate events.

This is what I tried so far (I'm using jQuery):

$(function() {
  console.log('document ready');

  setTimeout(function() {
    window.onpopstate = function(event) {
      // Do something here
    }, 10);
});

Basically I try to bind my listener function to popstate late enough to be not bound on page load, only later.

This seems to work, however, I don't like this solution. I mean, how can I be sure that the timeout chosen for setTimeout is big enough, but not too big (because I don't want it to wait too much).

I hope there is a smarter solution!

解决方案

Check for boolean truth of event.state in popstate event handler:

window.addEventListener('popstate', function(event) {
    if (event.state) {
        alert('!');
    }
}, false);

To ensure this will work, always specify a non-null state argument when calling history.pushState() or history.replaceState(). Also, consider using a wrapper library like History.js that provides consistent behavior across browsers.

这篇关于加载页面时的window.onpopstate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆