Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. ServiceWorkerGlobalScope
  4. fetch

ServiceWorkerGlobalScope: fetch event

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨April 2018⁩.

Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.

Note: This feature is only available inService Workers.

Thefetch event of theServiceWorkerGlobalScope interface is fired in the service worker's global scope when the main app thread makes a network request. It enables the service worker to intercept network requests and send customized responses (for example, from a local cache).

This event is not cancelable and does not bubble.

Syntax

Use the event name in methods likeaddEventListener(), or set an event handler property.

js
addEventListener("fetch", (event) => { })onfetch = (event) => { }

Description

Thefetch event is fired in the service worker's global scope when the main app thread makes a network request. This includes not only explicitfetch() calls from the main thread, but also implicit network requests to load pages and subresources (such as JavaScript, CSS, and images) made by the browser following page navigation.

The event handler is passed aFetchEvent object, which provides access to the request as aRequest instance.

TheFetchEvent also provides arespondWith() method, that takes aResponse (or aPromise that resolves to aResponse) as a parameter.This enables the service worker event handler to provide the response that is returned to the request in the main thread.

For example, the service worker can return:

  • A locally cached response retrieved from theCache interface.
  • A response that the service worker synthesizes, using methods likeResponse.json() or theResponse() constructor.
  • A network error, using theResponse.error() method. This will cause thefetch() call to reject.

TherespondWith() method can only be called once for a given request. If multiplefetch event listeners are added, they will be called in the order they were registered until one of them callsrespondWith().

TherespondWith() method must be called synchronously: that is, you can't call it in athen handler.

Typically, afetch event handler will execute different strategies depending on features of the request such as its URL:

js
function strategy1() {  return fetch("picnic.jpg");}function strategy2() {  return Response.error();}const pattern1 = /^\/salamander/;const pattern2 = /^\/lizard/;self.addEventListener("fetch", (event) => {  const url = new URL(event.request.url);  if (pattern1.test(url.pathname)) {    event.respondWith(strategy1());  } else if (pattern2.test(url.pathname)) {    event.respondWith(strategy2());  }});

IfrespondWith() is not called in the handler, then the user agent automatically makes the original network request.For example, in the code above, all requests that do not matchpattern1 orpattern2 are made as if the service worker did not exist.

Event type

AFetchEvent.

Examples

Cache falling back to network

Thisfetch event handler first tries to find the response in the cache. If a response is found, it returns the cached response. Otherwise, it tries to fetch the resource from the network.

js
async function cacheThenNetwork(request) {  const cachedResponse = await caches.match(request);  if (cachedResponse) {    console.log("Found response in cache:", cachedResponse);    return cachedResponse;  }  console.log("Falling back to network");  return fetch(request);}self.addEventListener("fetch", (event) => {  console.log(`Handling fetch event for ${event.request.url}`);  event.respondWith(cacheThenNetwork(event.request));});

Cache only

Thisfetch event handler implements a "cache only" policy for scripts and stylesheets. If the request'sdestination property is"script" or"style", the handler only looks in the cache, returning an error if the response was not found.All other requests go through to the network.

js
async function cacheOnly(request) {  const cachedResponse = await caches.match(request);  if (cachedResponse) {    console.log("Found response in cache:", cachedResponse);    return cachedResponse;  }  return Response.error();}self.addEventListener("fetch", (event) => {  if (    event.request.destination === "script" ||    event.request.destination === "style"  ) {    event.respondWith(cacheOnly(event.request));  }});

Specifications

Specification
Service Workers Nightly
# dom-serviceworkerglobalscope-onfetch

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp