From 6a45fd1d7384286b2c54e582ade1021ab68b6eda Mon Sep 17 00:00:00 2001 From: Marcus Noble Date: Sun, 15 Oct 2017 07:48:59 +0100 Subject: [PATCH 1/2] Removed cache --- app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.js b/app.js index 6d52ffb..6988805 100644 --- a/app.js +++ b/app.js @@ -24,7 +24,7 @@ const port = process.env.PORT || 8000; const oneDay = 86400000; app.use(compress()); -app.use(express.static(__dirname + '/build', {maxAge: oneDay * 365})); +app.use(express.static(__dirname + '/build')); var md = markdown('commonmark', {html: true}); md.parser.use(emoji); From 0be1988a6567db57a459d0cb74b79851299f101b Mon Sep 17 00:00:00 2001 From: Marcus Noble Date: Sun, 15 Oct 2017 07:53:43 +0100 Subject: [PATCH 2/2] Added post about Service Worker caching --- ...17-10-15-quick-and-easy-offline-support.md | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/posts/2017-10-15-quick-and-easy-offline-support.md diff --git a/src/posts/2017-10-15-quick-and-easy-offline-support.md b/src/posts/2017-10-15-quick-and-easy-offline-support.md new file mode 100644 index 0000000..a016783 --- /dev/null +++ b/src/posts/2017-10-15-quick-and-easy-offline-support.md @@ -0,0 +1,39 @@ +--- +layout: post.html +title: Quick & easy offline support +date: 2017-10-15 +tags: +summary: "Adding offline support to your site is easier than ever these days thanks to service workers." +--- +Adding offline support to your site is easier than ever these days thanks to service workers. + +I recently added offline support to my blog with a small service worker using a 'stale-while-revalidate' technique that will always serve up a cached resource to the user if available, if not it will fall back to the normal network response. The beauty of this technique is that it always attempts to perform the network response and will cache the up-to-date response for use next time. + +```javascript +/* 📄 service-worker.js */ + +var CACHE = 'v1'; + +// Intercept all network requests +self.addEventListener('fetch', function(event) { + event.respondWith(fetchAndCache(event)); +}); + +function fetchAndCache(event) { + return caches.open(CACHE).then(function (cache) { + return cache.match(event.request).then(function(response) { + // Fetch from the network regardless of a cached resource + var fetchResponse = fetch(event.request) + .then(function(networkResponse) { + // Cache the up-to-date resource + cache.put(event.request, networkResponse.clone()); + return networkResponse; + }); + // Return the cached response if it exists or fallback to the network + return response || fetchResponse; + }); + }); +} +``` + +**NOTE:** Make sure you have cache headers appropriately set. I spent a good chunk of time trying to debug why the cache wasn't updating and realised it was due to a high `max-age` header being set on the resource.