sw.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // we'll version our cache (and learn how to delete caches in
  2. // some other post)
  3. let cacheName = 'v1.1::static';
  4. const pageCached = [
  5. '/',
  6. '/index.html',
  7. '/manifest.json',
  8. '/sw.js',
  9. 'data/contacts.json',
  10. '/tools.ico',
  11. '/css/mobiparc.css',
  12. '/js/mobiparc.js',
  13. '/js/jquery-3.2.1.min.js',
  14. '/js/jquery-ui.min.js',
  15. '/js/handlebars.min.js',
  16. '/img/tools_512.png',
  17. '/img/tools_128.png',
  18. '/img/tools.svg',
  19. ];
  20. self.addEventListener('install', e => {
  21. // once the SW is installed, go ahead and fetch the resources
  22. // to make this work offline
  23. e.waitUntil(
  24. caches.open(cacheName).then(cache => {
  25. return cache.addAll(pageCached).then(() => self.skipWaiting());
  26. })
  27. );
  28. });
  29. self.addEventListener('activate', function (e) {
  30. //console.log('[ServiceWorker] Activate');
  31. e.waitUntil(
  32. caches.keys().then(keyList => {
  33. return Promise.all(keyList.map(key => {
  34. if (key !== cacheName) {
  35. //console.log('[ServiceWorker] Removing old cache', key);
  36. return caches.delete(key);
  37. }
  38. }));
  39. })
  40. );
  41. return self.clients.claim();
  42. });
  43. // when the browser fetches a url, either response with
  44. // the cached object or go ahead and fetch the actual url
  45. self.addEventListener('fetch', event => {
  46. event.respondWith(
  47. // ensure we check the *right* cache to match against
  48. caches.open(cacheName).then(cache => {
  49. return cache.match(event.request).then(res => {
  50. return res || fetch(event.request)
  51. });
  52. })
  53. );
  54. });