Integration of Google Workbox using webpack in PWA Part 2 custom implementation

You can also write your custom service worker code with workbox with importScript option. We will use custom plugins and modules of workbox inside our custom script.

Now we know how to write GenerateSW plugin in webpack as discussed thoroughly in my article: https://medium.com/@chahat.middha/integration-of-google-workbox-using-webpack-in-native-app-pwa-part-1-1d40a85f21ba

We will add just one line inside the plugin GenerateSW written below:

importScripts: [‘/dist/offline.js’],

In our build directory ‘/dist’, we have our custom file offline.js which will be imported in precache manifest inside service worker.

You can learn about all the modules and plugins from workbox on https://developers.google.com/web/tools/workbox/modules/

We have already use workbox precache in our first article, now we will use workbox strategies, background sync, google analytics, routing in our custom code.

  1. Workbox Strategies: There are 5 type of strategies:
    a. Stale-While-Revalidate — Using this strategy user will get Cached response first and while in background cache will update from server if there are some changes found response from server vs response from cache storage. 
    b. Cache First (Cache Falling Back to Network) — If you need on cached data first irrespective of new data, like some features are once cached and never change, in that case we can use this strategy, like we only rely on cache storage in this case.
    c. Network First (Network Falling Back to Cache) — When you first want network response and if network not available then you will get response from cache.
    d. Network Only — If specific request can only be fulfilled from network then use this strategy.
    e. Cache Only — When you need on cached response from cache storage use this strategy.
    Examples available on https://developers.google.com/web/tools/workbox/modules/workbox-strategies. Stale-while-Revalidate strategy example:
    workbox.routing.registerRoute(/\/(.*)/,workbox.strategies.staleWhileRevalidate({
    cacheName: “myPwa”,
     plugins: [
     new workbox.cacheableResponse.Plugin({
     “statuses”:[0,200]
     }),
     new workbox.expiration.Plugin({
     maxEntries:200,
     purgeOnQuotaError: true,
     }),
     ]}), ‘GET’
    );

2. Workbox Background Sync: When your request fails in case network now available, then Background Sync API will store the info in IndexedDB and will execute when network is available again. Its a plugin which you can add in your register route like:
const bgSyncPlugin = new workbox.backgroundSync.Plugin('myQueueName', {
 maxRetentionTime: 24 * 60 // Retry for max of 24 Hours
});

workbox.routing.registerRoute(
 /\/api\/.*\/*.json/,
 workbox.strategies.networkOnly({
 plugins: [bgSyncPlugin]
 }),
 'GET'
);

3. Google Analytics API: When in offline mode those request of ga that fails will be stored and executed later. You can register it like:
workbox.googleAnalytics.initialize({
 parameterOverrides: {
 cd1: ‘offline’,
 },
});

4. Routing: We can register a route and add its handler type also. You can read more about this on: https://developers.google.com/web/tools/workbox/modules/workbox-routing

For example:
workbox.routing.registerRoute(/\/apiv2(.*)/, args => {return apiHandler.handle(args);});

const apiHandler = workbox.strategies.networkFirst({

cacheName: ‘api’,

plugins: [

new workbox.expiration.Plugin({

maxEntries: 100,

maxAgeSeconds: 60 * 60 * 24 * 7, // 1 week

purgeOnQuotaError: true,

}),

bgSyncPlugin
]});

So as we have discussed a few important functions of workbox library. And workbox. I will do more research and write more posts on some advanced topics later.