Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. "use strict";
  2.  
  3. // check logs at: chrome://serviceworker-internals/
  4.  
  5. const CACHE = "my-cache-1";
  6.  
  7. // self: ServiceWorkerGlobalScope
  8. self.addEventListener("activate", ev => {
  9. // required for fetch hook??
  10. ev.waitUntil(clients.claim());
  11. }, false);
  12. self.addEventListener("fetch", ev => {
  13. console.log(`fetch ${ev.request.url}`);
  14. ev.respondWith(caches.open(CACHE).then(cache => {
  15. console.log("cache opened");
  16. return cache.match(ev.request).then(res => {
  17. console.log(`Cache ${res ? "" : "not"} found: ${ev.request.url}`);
  18. // response would be null, if throught to fetch() when null
  19. return res ? res : fetch(ev.request);
  20. });
  21. }));
  22. }, false);
  23. self.addEventListener("message", ev => {
  24. doAction(ev.data).catch(console.error);
  25. }, false);
  26.  
  27. function doAction({action, url, as}) {
  28. console.log(action, url, "as", as);
  29. switch (action) {
  30. case "cache": return doCache(url, as);
  31. case "remove": return doRemove(url, as);
  32. default: return Promise.reject(Error(`invalid action: ${action}`));;
  33. }
  34. }
  35. function doCache(url, as) {
  36. const req = new Request(url, {mode: "no-cors"});
  37. return caches.open(CACHE).
  38. then(cache => Promise.all([
  39. fetch(req).then(res => cache.put(url, res)),
  40. fetch(req).then(res => cache.put(as, res)),
  41. ]));
  42. }
  43. function doRemove(url, as) {
  44. return caches.open(CACHE).
  45. then(cache => Promise.all([cache.delete(url), cache.delete(as)]));
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement