sw.js (1412B)
1 // sw.js - service worker de la PWA: guarda la app entera en cache para abrirla sin 2 // internet (las partidas locales no necesitan servidor). @VERSION@ lo reemplaza 3 // `make web` con el hash del wasm: cada version nueva usa otra cache y borra la vieja, 4 // y el .js y el .wasm siempre salen de la misma. 5 var CACHE = 'catan-@VERSION@'; 6 var FILES = ['./', 'index.html', 'index.js', 'index.wasm', 'manifest.json', 'icon-192.png', 'icon-512.png']; 7 8 self.addEventListener('install', function (e) { 9 // cache: 'reload' saltea la cache HTTP del navegador: si no, podia quedar un index.js 10 // viejo junto a un index.wasm nuevo 11 e.waitUntil(caches.open(CACHE).then(function (c) { 12 return c.addAll(FILES.map(function (f) { return new Request(f, { cache: 'reload' }); })); 13 }).then(function () { return self.skipWaiting(); })); 14 }); 15 16 self.addEventListener('activate', function (e) { 17 e.waitUntil(caches.keys().then(function (keys) { 18 return Promise.all(keys.filter(function (k) { return k !== CACHE; }).map(function (k) { return caches.delete(k); })); 19 }).then(function () { return self.clients.claim(); })); 20 }); 21 22 self.addEventListener('fetch', function (e) { 23 if (e.request.method !== 'GET') return; 24 var url = new URL(e.request.url); 25 if (url.origin !== location.origin) return; 26 e.respondWith(caches.match(e.request, { ignoreSearch: true }).then(function (r) { 27 return r || fetch(e.request); 28 })); 29 });