Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Forked from bakoushin/sw-await.js
Last active May 7, 2020 12:22
Show Gist options
  • Save jrobinsonc/e73e426d8b5ad0923453537d05a00f6e to your computer and use it in GitHub Desktop.
Save jrobinsonc/e73e426d8b5ad0923453537d05a00f6e to your computer and use it in GitHub Desktop.
Service Worker: Promises vs Async/Await
const version = 1;
const appPrefix = 'myApp-';
const staticCacheName = appPrefix + 'static-v' + version;
const imagesCacheName = appPrefix + 'content-imgs';
var allCaches = [
staticCacheName,
imagesCacheName
];
self.addEventListener('message', event => {
if (event.data.action == 'skipWaiting') {
self.skipWaiting();
}
});
self.addEventListener('install', event => {
event.waitUntil(async () => {
const cache = await caches.open(staticCacheName);
await cache.addAll([
'/',
'script.js',
'style.css'
]);
}());
});
self.addEventListener('activate', event => {
event.waitUntil(async () => {
const keys = await caches.keys();
const deletions = keys
.filter(key => key.startsWith(appPrefix) && !allCaches.includes(key))
.map(key => caches.delete(key));
for (const success of deletions) {
await success;
}
}());
});
self.addEventListener('fetch', async event => {
let url = new URL(event.request.url);
let response = caches.match(url) || fetch(event.request);
event.respondWith(await response);
});
const version = 1;
const appPrefix = 'myApp-';
const staticCacheName = appPrefix + 'static-v' + version;
const imagesCacheName = appPrefix + 'content-imgs';
var allCaches = [
staticCacheName,
imagesCacheName
];
self.addEventListener('message', event => {
if (event.data.action == 'skipWaiting') {
self.skipWaiting();
}
});
self.addEventListener('install', event => {
event.waitUntil(
caches.open(staticCacheName).then(cache => {
return cache.addAll([
'/',
'script.js',
'style.css'
]);
})
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(keys
.filter(key => key.startsWith(appPrefix) && !allCaches.includes(key))
.map(key => caches.delete(key))
);
})
);
});
self.addEventListener('fetch', event => {
let url = new URL(event.request.url);
event.respondWith(
caches.match(url).then(response => {
return response || fetch(event.request);
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment