Service Workers
latviancoder.github.io
Service Worker
-
script file
-
runs in background
-
separate from a webpage
Features
-
rich offline experience
-
background sync
-
push notifications
:sadface:
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return setOfCachedUrls(cache).then(function(cachedUrls) {
return Promise.all(
Array.from(urlsToCacheKeys.values()).map(function(cacheKey) {
// If we don't have a key matching url in the cache already, add it.
if (!cachedUrls.has(cacheKey)) {
var request = new Request(cacheKey, {credentials: 'same-origin'});
return fetch(request).then(function(response) {
// Bail out of installation unless we get back a 200 OK for
// every request.
if (!response.ok) {
throw new Error('Request for ' + cacheKey + ' returned a ' +
'response with status ' + response.status);
}
return cleanResponse(response).then(function(responseToCache) {
return cache.put(cacheKey, responseToCache);
});
});
}
})
);
});
})
);
});
Shit is hard
- versioning
- browser cache busting
- caching strategies
- etc
sw-precache
sw-toolbox
staticFileGlobs: [
rootDir + '/css/**.css',
rootDir + '/**.html',
rootDir + '/images/**.*',
rootDir + '/js/**.js'
]
runtimeCaching: [{
urlPattern: /^https:\/\/jsonplaceholder\.typicode\.com\/users/,
handler: 'networkFirst'
}]
push notifications?
- tab opened, browser not closed
- push & notification api
Fragen?
Service Workers
By Sergey Ryzhov
Service Workers
- 535