Skip to content

Instantly share code, notes, and snippets.

@chidindu-ogbonna
Created April 30, 2019 11:22
Show Gist options
  • Save chidindu-ogbonna/4dfbd1e622d646381b77ded29da9d37c to your computer and use it in GitHub Desktop.
Save chidindu-ogbonna/4dfbd1e622d646381b77ded29da9d37c to your computer and use it in GitHub Desktop.
Including workbox in service workers
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.setConfig({ debug: true }); // show debugging even during development
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
console.log("%c Workbox is activated", "font-size: 30px; color: blue");
// Enable offline analytics
workbox.googleAnalytics.initialize();
// Fonts: Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
workbox.routing.registerRoute(
/^https:\/\/fonts\.googleapis\.com/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: "google-fonts-stylesheets"
})
);
// Fonts: Cache the underlying font files with a cache-first strategy for 1 year.
workbox.routing.registerRoute(
/^https:\/\/fonts\.gstatic\.com/,
new workbox.strategies.CacheFirst({
cacheName: "google-fonts-webfonts",
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200]
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 30
})
]
})
);
// Images: use a cache-first images, by matching against a list of known extensions.
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg|webp|svg)$/,
new workbox.strategies.CacheFirst({
cacheName: "images",
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60 // 30 Days
})
]
})
);
// JS|CSS Using a stale-while-revalidate strategy for CSS and JavaScript files that aren't precached.
workbox.routing.registerRoute(
/\.(?:js|css)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: "static-resources"
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment