Guest User

Untitled

a guest
Apr 22nd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. const cacheName = 'blogCache';
  2. const offlineUrl = '/offline/';
  3. const adminPageSlug = '/ghost';
  4.  
  5. /**
  6. * The event listener for the service worker installation
  7. */
  8. self.addEventListener('install', event => {
  9. event.waitUntil(
  10. caches.open(cacheName)
  11. .then(cache => cache.addAll([
  12. offlineUrl
  13. ]))
  14. );
  15. });
  16.  
  17. /**
  18. * Is the current request for an HTML page?
  19. * @param {Object} event
  20. */
  21. function isHtmlPage(event) {
  22. return event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html');
  23. }
  24.  
  25. /**
  26. * Is the current request for the admin portal resource
  27. * @param {Object} event
  28. */
  29. function isAdminPageResource(event) {
  30. return event.request.url.includes(adminPageSlug);
  31. }
  32.  
  33. /**
  34. * Fetch and cache any results as we receive them.
  35. */
  36. self.addEventListener('fetch', event => {
  37.  
  38. event.respondWith(
  39. caches.match(event.request)
  40. .then(response => {
  41. // Only return cache if it's not an HTML page or admin resources
  42. if (response && !isHtmlPage(event) && !isAdminPageResource(event)) {
  43. return response;
  44. }
  45.  
  46. return fetch(event.request).then(
  47. function (response) {
  48. // Dont cache if not a 200 response
  49. if (!response || response.status !== 200) {
  50. return response;
  51. }
  52.  
  53. let responseToCache = response.clone();
  54. caches.open(cacheName)
  55. .then(function (cache) {
  56. cache.put(event.request, responseToCache);
  57. });
  58.  
  59. return response;
  60. }
  61. ).catch(error => {
  62. // Check if the user is offline first and is trying to navigate to a web page
  63. if (isHtmlPage(event)
  64. ) {
  65. return caches.match(offlineUrl);
  66. }
  67. });
  68. })
  69. )
  70. ;
  71. });
Add Comment
Please, Sign In to add comment