FetchEvent: preloadResponse 属性
注意:此功能仅在 Service Workers 中可用。
preloadResponse 是 FetchEvent 接口的一个只读属性,它返回一个 Promise。如果触发了导航预加载,则此 Promise 会解析为导航预加载的 Response;否则,它会解析为 undefined。
如果启用了导航预加载,请求是 GET 请求,并且该请求是导航请求(由浏览器在加载页面和 iframe 时生成),则会触发导航预加载。
服务工作线程可以在其 fetch 事件处理程序中等待此 Promise,以便跟踪在服务工作线程启动期间发出的 fetch 请求的完成情况。
值
示例
此代码片段来自 使用导航预加载加速服务工作线程。
onfetch 事件处理程序监听 fetch 事件。当事件触发时,处理程序调用 FetchEvent.respondWith(),将一个 Promise 返回给受控制的页面。此 Promise 将使用请求的资源进行解析。
如果在 Cache 对象中存在匹配的 URL 请求,则代码返回从缓存中获取响应的 Promise。如果缓存中未找到匹配项,则代码返回 preloadResponse 中的 Promise。如果不存在匹配的缓存或预加载的响应,则代码从网络获取响应并返回关联的 Promise。
js
addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
// Respond from the cache if we can
const cachedResponse = await caches.match(event.request);
if (cachedResponse) return cachedResponse;
// Else, use the preloaded response, if it's there
const response = await event.preloadResponse;
if (response) return response;
// Else try the network.
return fetch(event.request);
})(),
);
});
规范
| 规范 |
|---|
| Service Workers # fetch-event-preloadresponse |
浏览器兼容性
加载中…