Skip to content

Instantly share code, notes, and snippets.

@jeffposnick
Created October 5, 2017 20:06
Show Gist options
  • Save jeffposnick/a8f7662b5d4677566c22b1cb82e6ec5f to your computer and use it in GitHub Desktop.
Save jeffposnick/a8f7662b5d4677566c22b1cb82e6ec5f to your computer and use it in GitHub Desktop.
Example of staleWhileRevalidate + broadcastCacheUpdate
const HN_URL = 'https://hackernewsapi.example.com/';
function updateUI(hnData) {
// Update the DOM.
}
async function init() {
const channel = new BroadcastChannel('hn-updates');
channel.addEventListener('message', async (event) => {
if (event.data.payload.updatedUrl === HN_URL) {
const response = await caches.match(HN_URL);
const hnData = await response.json();
updateUI(hnData);
}
});
const response = await fetch(HN_URL);
const hnData = await response.json();
updateUI(hnData);
}
// Other workboxSW usage...
workboxSW.registerRoute(
new RegExp('^https://hackernewsapi.example.com/'),
workboxSW.strategies.staleWhileRevalidate({
broadcastCacheUpdate: {
channelName: 'hn-updates',
},
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment