Workbox | Google Developers


Performance Icon

Stop waiting on the network! You can improve your web app's performance by caching and serving your files, powered by a service worker.

No Network Icon

Even on an unreliable connection, your web app can still work using the right runtime caching strategies.

Progressive Web App Logo

Looking to build a progressive web app? Workbox makes it easy to create an offline first experience.

Below are a few examples of the Workbox API demonstrating some of the common approaches developers take in their service workers.

Cache Google Fonts

Wish you could rely on Google Fonts being available offline after the user has visited your site? Add a quick rule to serve them from the cache.

 // Cache the Google Fonts stylesheets with a stale while revalidate strategy.
workbox.routing.registerRoute( /^https:\/\/fonts\.googleapis\.com/, workbox.strategies.staleWhileRevalidate({ cacheName: 'google-fonts-stylesheets', }),
); // Cache the Google Fonts webfont files with a cache first strategy for 1 year.
workbox.routing.registerRoute( /^https:\/\/fonts\.gstatic\.com/, workbox.strategies.cacheFirst({ cacheName: 'google-fonts-webfonts', plugins: [ new workbox.cacheableResponse.Plugin({ statuses: [0, 200], }), new workbox.expiration.Plugin({ maxAgeSeconds: 60 * 60 * 24 * 365, }), ], }),
); 

Cache JavaScript and CSS

Make your JS and CSS ⚡ fast by returning the assets from the cache, while making sure they are updated in the background for the next use.

 workbox.routing.registerRoute( /\.(?:js|css)$/, workbox.strategies.staleWhileRevalidate(),
); 

Cache Images

Images carry most of the weight for a web page. Use this rule to serve them quickly from the cache, while making sure you don’t cache them indefinitely, consuming your users' storage.

 workbox.routing.registerRoute( /\.(?:png|gif|jpg|jpeg|svg)$/, workbox.strategies.cacheFirst({ cacheName: 'images', plugins: [ new workbox.expiration.Plugin({ maxEntries: 60, maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days }), ], }),
); 

Precache your Files

Use Workbox to precache assets in your web app using our CLI, Node module or webpack plugin.

workbox wizard
const workboxBuild = require('workbox-build');
workboxBuild.generateSW({ swDest: './build/sw.js' globDirectory: './app', globPatterns: '**\/*.{js,css,html,png}',
});
const WorkboxPlugin = require('workbox-webpack-plugin'); // webpack config
{ plugins: [ // Other webpack plugins... new WorkboxPlugin() ]
}

Want offline analytics for your offline PWA? No problem.

 workbox.googleAnalytics.initialize();