If some of the topics in lesson 3 were new to you, we hope the resource links will help.
- Firefox: Service Workers (explained)
- Google Web Fundamentals: Overview
- Google Web Fundamentals: Service Workers Life Cycle
- Firefox: Cache
- Firefox: Service Worker API
- Firefox: CacheStorage
- High-performance service worker loading
- Google Chrome Developers video: Introduction to Service Workers
- Mozilla Service Workers examples
- JavaScript Promises for Dummies
- Jake Archibald: The offline cookbook
- Service Workers 101
- Google Workbox Libraries Collection of tools and helpers for working with Service Worker
- Zack Argyle (Pinterest) Utilities for creating, testing and experimenting with Service Workers
The service worker intercepts all requests the user makes. It can send the request straight to the server or first try to load cached data while requesting new data from the server.
if(navigator.serviceWorker) {
navigator.serviceWorker.register('path-to-sw')
.then(function(registeration) {
// console.log('Service worker successfully registered')
})
.catch(function(error) {
// console.log('Service worker failed to register')
});
}
The following properties are available on the registration object and represent its life cycle:
registration.installing
: either null or ServiceWorker object.registration.waiting
: either null or ServiceWorker object.registration.active
: either null or ServiceWorker object with state 'activated'.
Note: registration.active === navigator.serviceWorker.controller
except if force refresh is used: [Ctrl] + Refresh.
caches.open(‘cache_store_name’).then(function(cache) {
return cache.addAll(urlsToCache);
})
It is possible to use these three ways to store information in cache:
cache.add(request)
: stores single requestcache.addAll(request)
: stores an array of requestscache.put(request, response)
: stores a single request and its response
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
It is possible to use these 2 ways to fetch cached data:
caches.match(cache_name)
: Matches a single request and return a promisecaches.matchAll(cache_name)
: Matches an array and returns a promise
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
return cacheName.startsWith('wittr-') && cacheName != static_cache_name;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
caches.delete(cache_name)
: finds cache with given name and return a promisecaches.keys()
: returns a promise with an array of cache keys
self.addEventListener('install', function(event) {
event.waitUntil(
// Promise
)
})
self.addEventListener('activate', function(event) {
event.waitUntil(
// Promise
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
// Response
// you can use event.request to match from caches or fetch from network
)
})
self.addEventListener('message', function(event) {
// event.data
})