哈希未更改时触发异步onHashChange [英] Asynchronous onHashChange fires when hash has not changed

查看:54
本文介绍了哈希未更改时触发异步onHashChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 onHashChange 在Firefox 3.6.13中发生散列没有改变.在以下情况下,我更改了哈希,然后立即注册了一个自定义哈希更改回调.注册回调后,我没有更改哈希,但是尽管如此,我的回调已被触发.

I am seeing onHashChange fire in Firefox 3.6.13 when the hash has not changed. In the following scenario, I change the hash and then immediately afterwards register a custom hash change callback. I do not change the hash after registering the callback, but nontheless, my callback is fired.

  1. window.location + ='#newHash'导致地址栏更新立即地.
  2. Firefox注意哈希值改变并准备开枪异步onHashChange回调,这是一个空函数观点.
  3. 我注册了自己的自定义哈希更改回调: window.onhashchange = function(){console.info('自定义哈希打回来');};
  4. 最后是浏览器产生控制以进行异步事件.它触发onHashChange回调它在步骤2中安排的时间.
  1. window.location += '#newHash' causes the address bar to update immediately.
  2. Firefox notes the hash change and gets ready to fire an asynchronous onHashChange callback, which is an empty function at this point.
  3. I register my own custom hash change callback: window.onhashchange = function() { console.info('custom hash callback'); };
  4. Finally the browser yields control to do asynchronous events. It fires the onHashChange callback it scheduled in step 2.

这是我的真实代码的简化示例.我真正的回调实际上是通过AJAX更新数据库的,所以这种意外的哈希更改触发会给服务器带来不必要的负担,并且在逻辑上是不正确的.

This is a simplified example of my real code. My real callback actually updates the database through AJAX, so this unexpected hash change triggering puts unnecessary burden on the server and is just logically incorrect.

有人可以证明上述情况确实在发生,而不是其他一些编码错误吗?混淆了针对Mozilla提交的错误,该错误已标记为已解决/固定的.我不知道FF 3.6.13是否已经具有同步修补程序,或者FF的未来版本将进行此更改.

Can someone verfiy that the above scenario is indeed happening, rather than some other coding error? It's confusing that the bug filed against Mozilla to make onHashChange synchronous has been marked resolved/fixed. I don't know if FF 3.6.13 already has the synchronous fix or what future version of FF will have this change.

推荐答案

如果您阅读了链接到的bug的注释,就会发现该行为已恢复为异步.

If you read the comments on the bug you linked to, you'll see that the behaviour was reverted back to being asynchronous.

获得所需行为的一种方法是将更改包装到 window.setTimeout 函数中的 window.onhashchange 中,超时为0,对于例如:

One way to get the behaviour that you want would be to wrap the change to window.onhashchange in a window.setTimeout function, with a timeout of 0, for example:

window.location += '#newHash';
window.setTimeout(function() {
    window.onhashchange = function() { console.info('custom hash callback'); }
}, 0);

这篇关于哈希未更改时触发异步onHashChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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