ServiceWorkerGlobalScope: fetch イベント
fetch イベントは fetch() メソッドが呼び出されたときに発生します。
このイベントはキャンセル不可で、バブリングしません。
構文
このイベント名を addEventListener() 等のメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。
js
addEventListener("fetch", (event) => {});
onfetch = (event) => {};
イベント型
一般的な Event です。
例
このコードスニペットは、service worker prefetch の例(prefetch の例のライブ版を参照してください)からのものです。 onfetch イベントハンドラーは fetch イベントを監視します。イベントが発生した時、コードは Cache オブジェクト内で、最初に一致したリクエストに対して解決するプロミスを返します。もし、何も一致しなかった場合は、コードはネットワークからレスポンスを読み取ります。
さらに、このコードは fetch() 操作で発生した例外を処理しています。 HTTP のエラーレスポンス(たとえば、404)は、例外を引き起こさないことに注意してください。適切なエラーコードセットを持った通常のレスポンスオブジェクトを返します。
js
self.addEventListener("fetch", (event) => {
console.log(`Handling fetch event for ${event.request.url}`);
event.respondWith(
caches.match(event.request).then((response) => {
if (response) {
console.log("Found response in cache:", response);
return response;
}
console.log("No response found in cache. About to fetch from network…");
return fetch(event.request)
.then((response) => {
console.log("Response from network is:", response);
return response;
})
.catch((error) => {
console.error(`Fetching failed: ${error}`);
throw error;
});
})
);
});
仕様書
| Specification |
|---|
| Service Workers # dom-serviceworkerglobalscope-onfetch |
ブラウザーの互換性
BCD tables only load in the browser