Javascript jquery:卸载还是卸载之前?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4376596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: unload or beforeunload?
提问by Bin Chen
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:
当用户从当前页面导航离开时,我想向服务器发布一条消息,我现在正在使用 .unload 但结果不可靠,即使在其文档中说是真的:
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.
unload 事件的确切处理因浏览器版本而异。例如,某些版本的 Firefox 会在点击链接时触发该事件,但不会在窗口关闭时触发。在实际使用中,应该在所有支持的浏览器上测试行为,并与专有的 beforeunload 事件进行对比。
Should I use beforeunload event? Is it reliable?
我应该使用 beforeunload 事件吗?它可靠吗?
回答by Nick Craver
Yes, beforeunload
is more reliable, but be sure to assign it directly (not bound through jQuery), like this:
是的,beforeunload
更可靠,但一定要直接赋值(不要通过jQuery绑定),像这样:
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.
该unload
事件本身并不意味着要完成的工作,对象只是清理......作为垃圾收集器变得越来越好,还有一个供浏览器,甚至解雇的原因不太unload
事件。
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.
还要注意,对于您的特定情况,您必须向服务器发出同步请求……否则浏览器仍然不会等待 AJAX 调用完成。