diff --git a/source/sw.js b/source/sw.js index 7410aae..416494e 100644 --- a/source/sw.js +++ b/source/sw.js @@ -28,21 +28,35 @@ const ASSETS = [ "assets/scripts/ReviewDetails.js", ]; +/** + * Adds the install listener where the app assets are added to the cache + */ self.addEventListener("install", async () => { + // open the cace const cache = await caches.open(CACHE_NAME); + // add all elements in ASSETS to the cache, these are all the files requried for the app to run await cache.addAll(ASSETS); }); +/** + * Adds an event listener on fetch events to serve cached resources while offline + * Uses a network first structure to prioritize fetching from network in case of app updates. + * If there are important updates, we want the user to get those if possible. + */ self.addEventListener("fetch", (event) => { - console.log(`fetching: ${event.request.url}`); + // add a response to the fetch event event.respondWith(caches.open(CACHE_NAME).then((cache) => { + // try to return a network fetch response return fetch(event.request).then((fetchedResponse) => { + // if there is a response, add it to the cache cache.put(event.request, fetchedResponse.clone()); - console.log(typeof(fetchedResponse)); + // return the network response return fetchedResponse; }).catch(() => { - console.log(cache.match(event.request, {ignoreVary: true})); - return cache.match(event.request, {ignoreVary: true}); + // If there is not a network response, return the cached response + // The ignoreVary option is used here to fix an issue where the service worker + // would not serve certain requests unless the page was refreshed at least once + return cache.match(event.request, {ignoreVary: true}); }); })); }); diff --git a/specs/adrs/120222-serviceworker-netfirst.md b/specs/adrs/120222-serviceworker-netfirst.md new file mode 100644 index 0000000..f1f87a2 --- /dev/null +++ b/specs/adrs/120222-serviceworker-netfirst.md @@ -0,0 +1,19 @@ +# Use a network first cache second for service worker architecture + +- Status: in consideration +- Deciders: Arthur Lu +- Date: 12 / 02 / 22 + +## Decision Drivers + +- Need to balance the need for user ease of use and local first priority +- Users should expect to update their app easily when they have network, but may not be expected to know how to perform a hard refresh +- Local first priority means we should avoid unnecessary network activity when possible + +## Considered Options +- Network first cache second +- Cache first network second + +## Decision Outcome + +Chosen Option: TBD \ No newline at end of file