Fli*_*imm 6 javascript browser fetch-api
浏览器现在提供Fetch API,您可以通过 JavaScript 发出网络请求,如下所示:
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
Run Code Online (Sandbox Code Playgroud)
如果用户关闭调用fetch和履行承诺之间的选项卡,会发生什么?浏览器会丢弃请求吗?如果对 的调用fetch发生在unload或beforeunload事件中怎么办?
我知道sendBeaconAPI 调用就是用于此目的的,但我想知道sendBeacon现在我们有了fetch.
看看keepalive以下选项fetch:
该
keepalive选项可用于允许请求比页面存活时间更长。Fetch with thekeepaliveflag 是 API 的替代品Navigator.sendBeacon()。
这是一个例子:
await fetch("/example", {keepalive: true});
Run Code Online (Sandbox Code Playgroud)
与使用 发送的请求相比,使用fetch和 该keepalive选项发送的请求具有高优先级navigator.sendBeacon。APIfetch也更加灵活并提供更多选项。如果没有keepalive,则无法保证在用户关闭页面时请求将完成。
fetch()在 MDN 上