Created
September 2, 2021 15:28
-
-
Save Chrisa0418/dc52fd8448c508c94aa92e79df9dae72 to your computer and use it in GitHub Desktop.
Vue PWA ServiceWorker (Offline and Cache)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @license | |
* steveyerigan.com | |
* Copyright 2021 Inc. All rights reserved. | |
* | |
*/ | |
var dataCacheName = 'steve-pwa'; | |
var cacheName = 'steve-pwa'; | |
var filesToCache = [ | |
'/', | |
'/index.html' | |
]; | |
self.addEventListener('install', function(e) { | |
console.log('[ServiceWorker] Install'); | |
e.waitUntil( | |
caches.open(cacheName).then(function(cache) { | |
console.log('[ServiceWorker] Caching app shell'); | |
return cache.addAll(filesToCache); | |
}) | |
); | |
}); | |
self.addEventListener('activate', function(e) { | |
console.log('[ServiceWorker] Activate'); | |
e.waitUntil( | |
caches.keys().then(function(keyList) { | |
return Promise.all(keyList.map(function(key) { | |
if (key !== cacheName && key !== dataCacheName) { | |
console.log('[ServiceWorker] Removing old cache', key); | |
return caches.delete(key); | |
} | |
})); | |
}) | |
); | |
}); | |
self.addEventListener('fetch', function(event) { | |
event.respondWith( | |
caches.match(event.request) | |
.then(function(response) { | |
// Cache hit - return response | |
if (response) { | |
return response; | |
} | |
// IMPORTANT: Clone the request. A request is a stream and | |
// can only be consumed once. Since we are consuming this | |
// once by cache and once by the browser for fetch, we need | |
// to clone the response | |
var fetchRequest = event.request.clone(); | |
return fetch(fetchRequest).then( | |
function(response) { | |
// Check if we received a valid response | |
if(!response || response.status !== 200) { | |
return response; | |
} | |
// IMPORTANT: Clone the response. A response is a stream | |
// and because we want the browser to consume the response | |
// as well as the cache consuming the response, we need | |
// to clone it so we have 2 stream. | |
var responseToCache = response.clone(); | |
caches.open(dataCacheName) | |
.then(function(cache) { | |
cache.put(event.request, responseToCache); | |
}); | |
return response; | |
} | |
); | |
}) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment