Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ---
- layout: null
- ---
- var currentCache = 'cache name';
- var coreCache = [
- {%- for post in site.posts -%}
- "{{ post.url }}",
- {%- endfor -%}
- {%- for page in site.html_pages -%}
- "{{ page.url }}",
- {%- endfor -%}
- "/scripts.js"
- ];
- var secondaryCache = [
- {%- for asset in site.static_files -%}
- {%- if asset.path contains '.woff2' -%}
- "{{ asset.path }}",
- {%- endif -%}
- {%- endfor -%}
- "/styles.css"
- ];
- self.addEventListener('install', function(event) {
- event.waitUntil(async function() {
- const cache = await caches.open(currentCache);
- cache.addAll(secondaryCache); // caches fonts in the background, without install being "dependant" on them
- await cache.addAll(coreCache); // more important stuff
- });
- });
- // If a request doesn't match anything in the cache, fallback to network and then add to cache!
- self.addEventListener('fetch', function(event) {
- event.respondWith(async function() {
- const cache = await caches.open(currentCache);
- const cachedResponse = await cache.match(event.request);
- if (cachedResponse) return cachedResponse;
- const networkResponse = await fetch(event.request);
- event.waitUntil(
- cache.put(event.request, networkResponse.clone())
- );
- return networkResponse;
- });
- });
- // update service worker if there is a new one
- self.addEventListener('activate', function(event) {
- var cacheWhitelist = [currentCache];
- event.waitUntil(
- caches.keys().then(function(cacheNames) {
- return Promise.all(
- cacheNames.map(function(cacheName) {
- if (cacheWhitelist.indexOf(cacheName) === -1) {
- return caches.delete(cacheName);
- }
- })
- );
- })
- );
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement