Offline First
ユーザーがトンネルに入っても、白画面を見せてはいけない。「オフライン恐竜」はもう見たくない。
Service Worker
ブラウザのバックグラウンドで動くJS。ネットワークリクエストを横取りしてキャッシュを返したり、オフライン対応を行う。
How it works (Proxy)
Service Workerは、ブラウザとネットワークの間に立つ「プロキシサーバー」のようなもの。全てのリクエストを検閲し、キャッシュを返すか、ネットワークに取りに行くかを判断できる。
// service-worker.js
// 1. Install (Cache assets)self.addEventListener('install', (e) => { e.waitUntil( caches.open('v1').then((cache) => { return cache.addAll(['/', '/style.css', '/script.js']); }) );});
// 2. Fetch (Intercept requests)self.addEventListener('fetch', (e) => { e.respondWith( caches.match(e.request).then((response) => { // Return cache if found, otherwise network return response || fetch(e.request); }) );});