CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-workbox-sw

Service worker library that provides an easy entry point to the Workbox ecosystem for Progressive Web Apps

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Workbox SW

Workbox SW is a service worker library that provides an easy entry point to the Workbox ecosystem for Progressive Web Apps. It creates a global workbox object that acts as a proxy to dynamically load and access other Workbox modules, simplifying the integration of service worker functionality without requiring individual module management.

Package Information

  • Package Name: workbox-sw
  • Package Type: npm
  • Language: JavaScript (ES modules)
  • Installation: npm install workbox-sw

Core Imports

For service worker environments, import via importScripts:

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

For module environments:

import 'workbox-sw';

Basic Usage

// Import the library (creates global workbox object)
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.3.0/workbox-sw.js');

// Configure Workbox (optional)
workbox.setConfig({
  debug: true,
  modulePathPrefix: '/custom/path/to/workbox-modules/'
});

// Use Workbox modules through the global object
workbox.precaching.precacheAndRoute([
  '/app.js',
  '/styles.css',
  '/index.html'
]);

workbox.routing.registerRoute(
  new RegExp('.*\\.(?:png|jpg|jpeg|svg|gif)'),
  new workbox.strategies.CacheFirst({
    cacheName: 'image-cache',
    plugins: [
      new workbox.expiration.ExpirationPlugin({
        maxEntries: 50,
      }),
    ],
  })
);

Architecture

Workbox SW is built around several key components:

  • Global Proxy Object: The workbox global acts as a proxy that automatically loads Workbox modules on first access
  • Dynamic Module Loading: Modules are loaded on-demand using importScripts() when their properties are accessed
  • CDN Integration: By default, modules are loaded from Google's CDN, with options for custom paths
  • Configuration System: Centralized configuration for debug mode, module paths, and loading behavior

Capabilities

Configuration

Configure Workbox behavior including debug mode and module loading paths.

/**
 * Configure Workbox settings before accessing any modules
 * @param {Object} options - Configuration options
 * @param {boolean} options.debug - Use dev builds if true, prod builds if false (default: true on localhost)
 * @param {string} options.modulePathPrefix - Custom path prefix for module loading
 * @param {ModulePathCallback} options.modulePathCb - Custom callback for determining module paths
 */
workbox.setConfig(options);

Manual Module Loading

Explicitly load Workbox modules to ensure availability.

/**
 * Manually load a Workbox module by name
 * @param {string} moduleName - Name of the module to load (e.g., 'workbox-precaching')
 */
workbox.loadModule(moduleName);

Dynamic Module Access

Access Workbox modules through property access on the global workbox object. Modules are loaded automatically on first access.

Background Sync

Access to workbox-background-sync module for offline background synchronization.

workbox.backgroundSync

Broadcast Update

Access to workbox-broadcast-update module for notifying clients of cache updates.

workbox.broadcastUpdate

Cacheable Response

Access to workbox-cacheable-response module for determining cacheable responses.

workbox.cacheableResponse

Core

Access to workbox-core module providing fundamental Workbox utilities.

workbox.core

Expiration

Access to workbox-expiration module for cache expiration management.

workbox.expiration

Google Analytics

Access to workbox-google-analytics module for offline Google Analytics support.

workbox.googleAnalytics

Navigation Preload

Access to workbox-navigation-preload module for navigation preload functionality.

workbox.navigationPreload

Precaching

Access to workbox-precaching module for precaching static assets.

workbox.precaching

Range Requests

Access to workbox-range-requests module for handling HTTP range requests.

workbox.rangeRequests

Routing

Access to workbox-routing module for request routing and interception.

workbox.routing

Strategies

Access to workbox-strategies module for caching strategies (CacheFirst, NetworkFirst, etc.).

workbox.strategies

Streams

Access to workbox-streams module for handling streaming responses.

workbox.streams

Recipes

Access to workbox-recipes module for common Workbox usage patterns.

workbox.recipes

Types

ModulePathCallback

Custom callback function for determining module paths.

/**
 * Callback function for customizing module paths
 * @callback ModulePathCallback
 * @param {string} moduleName - The name of the module to load (e.g., 'workbox-core')
 * @param {boolean} debug - When true, dev builds should be loaded, otherwise load prod builds
 * @returns {string} Path to the module file for importScripts()
 */

Usage Examples

Basic Service Worker Setup

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

// Precache static assets
workbox.precaching.precacheAndRoute([
  '/index.html',
  '/app.js',
  '/styles.css'
]);

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

Custom Configuration

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

// Use custom module path
workbox.setConfig({
  debug: false,
  modulePathPrefix: '/custom/workbox-modules/'
});

// Or use a custom callback
workbox.setConfig({
  modulePathCb: (moduleName, debug) => {
    const suffix = debug ? 'dev' : 'prod';
    return `/my-cdn/${moduleName}.${suffix}.js`;
  }
});

Preloading Modules

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

// Preload modules that might be needed later
workbox.loadModule('workbox-background-sync');
workbox.loadModule('workbox-routing');

// Now these modules are available immediately
workbox.backgroundSync.Queue('my-queue');

Error Handling

  • Configuration Error: setConfig() throws an error if called after any modules have been loaded
  • Module Loading Error: loadModule() logs a console error and re-throws if module loading fails
  • Network Errors: Module loading failures typically indicate network issues or incorrect CDN paths

Browser Support

  • Designed specifically for service worker environments
  • Requires support for ES6 Proxy objects
  • Uses importScripts() for dynamic module loading
  • Compatible with all modern browsers that support service workers

docs

index.md

tile.json