Advertisement
Guest User

Jekyll service worker

a guest
Mar 2nd, 2019
90
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ---
  2. layout: null
  3. ---
  4. var currentCache = 'cache name';
  5. var coreCache = [
  6.   {%- for post in site.posts -%}
  7.     "{{ post.url }}",
  8.   {%- endfor -%}
  9.   {%- for page in site.html_pages -%}
  10.     "{{ page.url }}",
  11.   {%- endfor -%}
  12.   "/scripts.js"
  13. ];
  14. var secondaryCache = [
  15.   {%- for asset in site.static_files -%}
  16.     {%- if asset.path contains '.woff2' -%}
  17.       "{{ asset.path }}",
  18.     {%- endif -%}
  19.   {%- endfor -%}
  20.   "/styles.css"
  21. ];
  22. self.addEventListener('install', function(event) {
  23.   event.waitUntil(async function() {
  24.   const cache = await caches.open(currentCache);
  25.   cache.addAll(secondaryCache); // caches fonts in the background, without install being "dependant" on them
  26.   await cache.addAll(coreCache); // more important stuff
  27.   });
  28. });
  29. // If a request doesn't match anything in the cache, fallback to network and then add to cache!
  30. self.addEventListener('fetch', function(event) {
  31.   event.respondWith(async function() {
  32.     const cache = await caches.open(currentCache);
  33.     const cachedResponse = await cache.match(event.request);
  34.     if (cachedResponse) return cachedResponse;
  35.     const networkResponse = await fetch(event.request);
  36.     event.waitUntil(
  37.       cache.put(event.request, networkResponse.clone())
  38.     );
  39.     return networkResponse;
  40.   });
  41. });
  42. // update service worker if there is a new one
  43. self.addEventListener('activate', function(event) {
  44.   var cacheWhitelist = [currentCache];
  45.   event.waitUntil(
  46.     caches.keys().then(function(cacheNames) {
  47.       return Promise.all(
  48.         cacheNames.map(function(cacheName) {
  49.           if (cacheWhitelist.indexOf(cacheName) === -1) {
  50.             return caches.delete(cacheName);
  51.           }
  52.         })
  53.       );
  54.     })
  55.   );
  56. });
Advertisement
RAW Paste Data Copied
Advertisement