javascript - 为什么异步 XMLHttpRequests 优于同步请求?

标签 javascript xmlhttprequest

<分区>

异步和同步之间有什么区别,这些区别对请求有何影响?

最佳答案

摘自关于 Synchronous and asynchronous requests 的 Mozilla 文章:

XMLHttpRequest supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons.

In short, synchronous requests block the execution of code and can leak memory and events. This can cause serious issues. The only viable reason to use synchronous requests is to more easily facilitate downloads within Web Workers.

异步请求是 XMLHttpRequest 存在的主要原因。 XMLHttpRequest 是 AJAX 的基础,AJAX 的理念是让您的 JavaScript 代码运行,您的用户可以对您的页面执行任何操作,同时您的 JavaScript 在后台与服务器通信。例如,Gmail 以这种方式加载您的电子邮件。

同步请求会阻止您的脚本在传输完成时运行。简而言之,当异步请求可用时,没有理由这样做。如果您的 Gmail 一直死机,那会很烦人,您不觉得吗?您很少(如果有的话)想要使用同步请求。

There are circumstances you must use a synchronous request ,但在这些情况之外,您可能完全没有理由发出同步请求,并且有充分的理由使用异步请求。

关于javascript - 为什么异步 XMLHttpRequests 优于同步请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16328120/

相关文章:

javascript - Angularjs View 不更新

javascript - 在子模块中看不到 Angular 4 组件

javascript - 未捕获的类型错误 : undefined is not a function on line var new_arr = filtered. 分割 (',' );

javascript - IOS 上的 xmlhttprequest 不发送请求?

javascript - 如何在我的 Firefox OS 应用程序的服务器中加载远程内容 - 在 Web 和 FxOS 设备中

go - 如何将空的 xmlns =""添加到请求的结构标记中?

javascript - 如何从 props.map 中删除空值

javascript - 执行随机 css 更改

excel - 如何从 Excel 宏 (vba) 使用 API 询问 ChatGPT?

android - 在 Android axios (XMLHttpRequest) 上使用阿拉伯语和波斯语在 React Native 中损坏的字符