Skip to content

Instantly share code, notes, and snippets.

@ngokevin
Last active March 12, 2023 09:52
Show Gist options
  • Save ngokevin/7eb03d90987c0ed03b873530c3b4c53c to your computer and use it in GitHub Desktop.
Save ngokevin/7eb03d90987c0ed03b873530c3b4c53c to your computer and use it in GitHub Desktop.
Service Worker Template - cache-else-network + network-else-cache
var VERSION = 'v1';
var cacheFirstFiles = [
// ADDME: Add paths and URLs to pull from cache first if it has been loaded before. Else fetch from network.
// If loading from cache, fetch from network in the background to update the resource. Examples:
// 'assets/img/logo.png',
// 'assets/models/controller.gltf',
];
var networkFirstFiles = [
// ADDME: Add paths and URLs to pull from network first. Else fall back to cache if offline. Examples:
// 'index.html',
// 'build/build.js',
// 'css/index.css'
];
// Below is the service worker code.
var cacheFiles = cacheFirstFiles.concat(networkFirstFiles);
self.addEventListener('install', event => {
event.waitUntil(
caches.open(VERSION).then(cache => {
return cache.addAll(cacheFiles);
})
);
});
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') { return; }
if (networkFirstFiles.indexOf(event.request.url) !== -1) {
event.respondWith(networkElseCache(event));
} else if (cacheFirstFiles.indexOf(event.request.url) !== -1) {
event.respondWith(cacheElseNetwork(event));
} else {
event.respondWith(fetch(event.request));
}
});
// If cache else network.
// For images and assets that are not critical to be fully up-to-date.
// developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/
// #cache-falling-back-to-network
function cacheElseNetwork (event) {
return caches.match(event.request).then(response => {
function fetchAndCache () {
return fetch(event.request).then(response => {
// Update cache.
caches.open(VERSION).then(cache => cache.put(event.request, response.clone()));
return response;
});
}
// If not exist in cache, fetch.
if (!response) { return fetchAndCache(); }
// If exists in cache, return from cache while updating cache in background.
fetchAndCache();
return response;
});
}
// If network else cache.
// For assets we prefer to be up-to-date (i.e., JavaScript file).
function networkElseCache (event) {
return caches.match(event.request).then(match => {
if (!match) { return fetch(event.request); }
return fetch(event.request).then(response => {
// Update cache.
caches.open(VERSION).then(cache => cache.put(event.request, response.clone()));
return response;
}) || response;
});
}
@mrcoles
Copy link

mrcoles commented May 3, 2019

@ngokevin quick question: Why isn’t line 37 wrapped in an else { … }? It appears that the event listener will always execute a fetch for the network resource regardless of whether it is cached or not (even if it still does/uses the caching).

@ceccun
Copy link

ceccun commented Sep 23, 2020

@ngokevin quick question: Why isn’t line 37 wrapped in an else { … }? It appears that the event listener will always execute a fetch for the network resource regardless of whether it is cached or not (even if it still does/uses the caching).

JS is synchronous. It will return and respond before the next line is executed. So it doesn't need to be wrapped in an else { ... }.

@gushogg-blake
Copy link

gushogg-blake commented Oct 26, 2020

JS is synchronous. It will return and respond before the next line is executed. So it doesn't need to be wrapped in an else { ... }

Just to clarify this for any future readers - JS won't return unless there is a return statement* - I'm guessing @stel-la misread/assumed there were returns on lines 33 and 35. So the code will execute line 37 regardless - this does seem to be a mistake.

  • functions also implicitly return undefined if the function doesn't explicitly return anything.

@ngokevin
Copy link
Author

Fixed, thanks!

@wilvoss
Copy link

wilvoss commented Nov 26, 2021

37 event.respondWith(fetch(event.request));

this line is breaking when offline as it's trying to fetch the base url "https://staging.siteexample.com" of the site. put another way, lines 32 and 34 don't catch this so the very first request, which is the base url ("https://staging.siteexample.com", fails to trigger either of those conditions, hence landing on the final line 37.

this then throws because the network is offline and the fetch can't do its job.

what am I missing?

@ngokevin
Copy link
Author

I deprecate this and recommend using workbox-strategies from Google. https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-strategies

@wilvoss
Copy link

wilvoss commented Nov 29, 2021

Ah okay - thanks for the reply!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment