FetchEvent
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
This is the event type for fetch
events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith()
method, which allows us to provide a response to this fetch.
Constructor
FetchEvent()
(en-US)-
Creates a new
FetchEvent
object. This constructor is not typically used. The browser creates these objects itself and provides them tofetch
event callbacks.
Properties
Inherits properties from its ancestor, Event
.
fetchEvent.clientId
(en-US) 읽기 전용-
The
id
(en-US) of the same-originclient
(en-US) that initiated the fetch. fetchEvent.preloadResponse
(en-US) 읽기 전용-
A
Promise
for aResponse
(en-US), or void if this is not a navigation, or navigation preload (en-US) is not enabled. fetchEvent.request
(en-US) 읽기 전용-
The
Request
the browser intends to make.
Methods
Inherits methods from its parent, ExtendableEvent
(en-US).
fetchEvent.respondWith()
-
Prevent the browser's default fetch handling, and provide (a promise for) a response yourself.
extendableEvent.waitUntil()
(en-US)-
Extends the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching.
Examples
This fetch event uses the browser default for non-GET requests. For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time.
addEventListener('fetch', event => {
// Let the browser do its default thing
// for non-GET requests.
if (event.request.method != 'GET') return;
// Prevent the default, and handle the request ourselves.
event.respondWith(async function() {
// Try to get the response from a cache.
const cache = await caches.open('dynamic-v1');
const cachedResponse = await cache.match(event.request);
if (cachedResponse) {
// If we found a match in the cache, return it, but also
// update the entry in the cache in the background.
event.waitUntil(cache.add(event.request));
return cachedResponse;
}
// If we didn't find a match in the cache, use the network.
return fetch(event.request);
}());
});
명세서
Specification |
---|
Service Workers # fetchevent-interface |
브라우저 호환성
BCD tables only load in the browser