-
-
Save jrobinsonc/e73e426d8b5ad0923453537d05a00f6e to your computer and use it in GitHub Desktop.
Service Worker: Promises vs Async/Await
This file contains 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
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); | |
}); |
This file contains 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
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