Get started with workbox-sw CDN

MIT licensed

Library for caching, network handling in JS apps: Service Worker-Workbox-SW.

Tags:
  • workbox
  • workboxjs
  • service worker
  • sw

Stable version

Copied!

How to start using workbox-sw CDN


// Register the service worker as soon as the page is loaded
self.registration = await navigator.serviceWorker.register('service-worker.js', { scope: '/' });

// Import Workbox SW and its modules
importScripts('https://cdn.cdnhub.io/workbox-sw/7.0.0/workbox-sw.js');
workbox.precaching.precacheAndRoute([
  // List of files to precache
  '/index.html',
  '/styles.css',
  '/main.js',
  // Add your assets here
]);

// Cache and route network requests
workbox.routing.registerRoute(
  /\.(?:json|xml)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'json-cache',
    plugins: [
      new workbox.expiration.Plugin({ maxEntries: 60, maxAgeSeconds: 30 * 24 * 60 * 60 }), // Cache for 30 days
    ],
  })
);

workbox.routing.registerRoute(
  /\.(?:png|jpg|jpeg|gif|svg)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'image-cache',
    plugins: [
      new workbox.expiration.Plugin({ maxEntries: 300, maxAgeSeconds: 30 * 24 * 60 * 60 }), // Cache for 30 days
    ],
  })
);

// Cache and route Google Fonts
workbox.routing.registerRoute(
  /^https:\/\/fonts\.googleapis\.com/,
  new workbox.strategies.CacheFirst({
    cacheName: 'google-fonts-cache',
    plugins: [
      new workbox.cacheableResponse.Plugin({ statuses: [0, 200] }),
      new workbox.expiration.Plugin({ maxEntries: 25, maxAgeSeconds: 60 * 60 * 24 * 30 }), // Cache for 30 days
    ],
  })
);

// Cache and route Google Analytics
workbox.routing.registerRoute(
  /^https:\/\/www.goog-analytics.com/,
  new workbox.strategies.NetworkFirst({
    cacheName: 'google-analytics-cache',
    plugins: [
      new workbox.cacheableResponse.Plugin({ statuses: [0, 200] }),
    ],
  })
);
Copied!
Copied!
Copied!

All versions