jquery:unload还是beforeunload? [英] jquery: unload or beforeunload?

查看:146
本文介绍了jquery:unload还是beforeunload?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户离开当前页面时向服务器发布消息,我现在正在使用.unload,但结果不可靠,即使在其文档中也是如此:

I want to post an message to the server when user navigate off from the current page, I am using .unload right now but the result is unreliable, even in its document is said true:


卸载事件
的确切处理因
浏览器的版本而异。例如,一些版本
的Firefox会在跟随
链接时触发事件,但不会在
窗口关闭时触发。在实际使用中,应该在所有
支持的浏览器上测试
行为,并使用专有的beforeunload
事件对比

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

我应该使用beforeunload事件吗?它可靠吗?

Should I use beforeunload event? Is it reliable?

推荐答案

是的, beforeunload 更可靠,但是一定要直接分配(不是通过jQuery绑定),如下所示:

Yes, beforeunload is more reliable, but be sure to assign it directly (not bound through jQuery), like this:

window.onbeforeunload = function() { /* do stuff */ };

卸载事件本身并不意味着为了完成工作,只清理对象......随着垃圾收集器变得越来越好,浏览器甚至没有理由触发卸载事件。

The unload event itself wasn't meant for work to be done, only cleanup of objects...as garbage collectors get better and better, there's less reason for the browser to even fire the unload event.

还要注意,对于您的特定情况,您必须向服务器发出同步请求...否则浏览器仍然不会等待AJAX​​调用完成。

Also be aware that for your specific case you'd have to make a synchronous request to the server...otherwise the browser still won't wait for the AJAX call to complete.

这篇关于jquery:unload还是beforeunload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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