workbox usage

linkaiyi
Follow

use function to parse request url

function matchFunction({ url }) {
  const pages = ['/', '/about'];
  return pages.includes(url.pathname);
}

workbox.routing.registerRoute(
  matchFunction,
  new workbox.strategies.CacheFirst({
    cacheName: 'html-cache'
  })
);

use a function as new handler

// Fallback to offline page if nothing is found in cache
var networkFirstHandler = workbox.strategies.networkFirst({
  cacheName: 'default',
  plugins: [
    new workbox.expiration.Plugin({
      maxEntries: 10
    }),
    new workbox.cacheableResponse.Plugin({
      statuses: [200]
    })
  ]
});

const matcher = ({event}) => event.request.mode === 'navigate';
const handler = (args) => networkFirstHandler.handle(args).then((response) => (!response) ? caches.match('/offline') : response);

workbox.routing.registerRoute(matcher, handler);
// End fallback offline

sample service-worker

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.2.0/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}

workbox.setConfig({
  debug: false
});

// workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);


workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'static-resources',
  }),
);

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
      }),
    ],
  }),
);

workbox.routing.registerRoute(
  new RegExp('https://fonts.(?:googleapis|gstatic).com/(.*)'),
  workbox.strategies.cacheFirst({
    cacheName: 'googleapis',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 30,
      }),
    ],
  }),
);

workbox.precaching.precacheAndRoute(
  [
    '/',
    '/offline',
  ],
  {
    directoryIndex: null,
  }
);

workbox.routing.registerRoute(
  /* my urls doesn't end in html, so i didn't found another way to 
  store only the html document except using the main route of my app as reg ex

example: http://localhost:8000/participation/id/title -> html for article
         http://localhost:8000/participation/ -> html for list of articles */

      new RegExp('participation/'), 
      workbox.strategies.networkFirst({
        cacheName: 'html-resources',
      })
    );

workbox.routing.registerRoute(
  ({ event }) => event.request.mode === 'navigate', //if the requests is to go to a new url
  ({ url }) => fetch(url.href,{credentials: 'same-origin'}).catch(() => caches.match('/offline')) //in case of not match send my to the offline page
);
Object has 0 attachments

Was this article helpful?

This article is viewed 12 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support