weixin_33720452 2015-03-26 15:43 采纳率: 0%
浏览 174

XHR同步弃用

According to xhr specs async: false is deprecated and modern user agents should start to warn about or even to throw exception.

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs.

I understand and agree with argument about "detrimental" effects. The main point about this deprecation is you can solve any of your tasks with async XHR. However, I can see at least two applications of sync XHR in browser:

1) window.onbeforeunload. Any async xhr is useless here since browser tab will close immediately. Example of usage XHR in onbeforeunload event is document "lock". User opened document in new tab and document is locked by him now. Everyone can view this doc in read-only. Then user closes tab and document should unlock. I don't see any solution with async request, until user agent is guaranted that async request will be performed, and, even more, will not be aborted after tab close.

2) click event on anchor (<a> tag). It's close to previous case because it's also closes current window in creates new one in the same tab. Let's say I just want to track click on critical links on page (but I beleive there are more noble examples of this event synchronous usage). The one workaround is to do e.preventDefault() in handler and then assign location manually, but this can break middle mouse button behavior (force open new tab).

The questions are: 1) Are user agents must complete async XHR even when tab is already closed? 2) Are there more smart solutions for my examples?

  • 写回答

1条回答 默认 最新

  • weixin_33671935 2015-11-04 23:29
    关注

    For the specific case of guaranteeing that HTTP data is sent before the page unloads, take a look at the experimental Beacon API. MDN even has a specific article discussing this use case.

    It is an asynchronous API but it guarantees that any data send through it will be sent even after the page unloads.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效