CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-workbox-precaching

This module efficiently precaches assets for Progressive Web Apps and service workers.

Pending
Overview
Eval results
Files

advanced-controller.mddocs/

Advanced Controller

The PrecacheController class provides fine-grained control over precaching behavior with methods for installation, activation, and cache management. Use this class when you need more control than the simple setup functions provide.

Capabilities

PrecacheController Class

Main controller class for efficient precaching of assets with full control over the caching lifecycle.

/**
 * Main controller class for efficient precaching of assets
 */
class PrecacheController {
  /**
   * Create a new PrecacheController instance
   * @param options - Configuration options
   */
  constructor(options?: PrecacheControllerOptions);

  /** The strategy used to cache assets and respond to fetch events */
  readonly strategy: Strategy;
}

Usage Examples:

import { PrecacheController } from "workbox-precaching";

// Basic controller
const precacheController = new PrecacheController();

// Controller with custom options
const customController = new PrecacheController({
  cacheName: "my-app-precache-v1",
  fallbackToNetwork: false,
  plugins: [
    {
      cacheKeyWillBeUsed: async ({ request, mode }) => {
        // Custom cache key logic
        return `${request.url}?v=1.0`;
      }
    }
  ]
});

Cache List Management

Methods for managing the list of assets to be precached.

/**
 * Adds items to precache list and sets up install/activate event listeners
 * @param entries - Array of entries to precache
 */
precache(entries: Array<PrecacheEntry | string>): void;

/**
 * Adds items to precache list with validation and duplicate removal
 * @param entries - Array of entries to add to the cache list
 */
addToCacheList(entries: Array<PrecacheEntry | string>): void;

Usage Examples:

const controller = new PrecacheController();

// Add entries and set up event listeners
controller.precache([
  { url: "/index.html", revision: "abc123" },
  "/static/styles.css"
]);

// Or just add to list without setting up listeners
controller.addToCacheList([
  { url: "/additional.js", revision: "def456" }
]);

Installation and Activation

Methods for handling service worker lifecycle events.

/**
 * Installs new and updated assets (call from service worker install event)
 * @param event - The install event from service worker
 * @returns Promise resolving to installation results
 */
install(event: ExtendableEvent): Promise<InstallResult>;

/**
 * Deletes outdated assets (call from service worker activate event)  
 * @param event - The activate event from service worker
 * @returns Promise resolving to cleanup results
 */
activate(event: ExtendableEvent): Promise<CleanupResult>;

Usage Examples:

const controller = new PrecacheController();

// In service worker
self.addEventListener('install', (event) => {
  event.waitUntil(
    controller.install(event).then((result) => {
      console.log('Updated URLs:', result.updatedURLs);
      console.log('Not updated URLs:', result.notUpdatedURLs);
    })
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    controller.activate(event).then((result) => {
      console.log('Deleted URLs:', result.deletedCacheRequests);
    })
  );
});

Query Methods

Methods for inspecting the current state of the precache.

/**
 * Returns mapping of precached URLs to their cache keys
 * @returns Map of URL to cache key
 */
getURLsToCacheKeys(): Map<string, string>;

/**
 * Returns list of all precached URLs
 * @returns Array of precached URLs
 */
getCachedURLs(): Array<string>;

/**
 * Returns cache key for a given URL
 * @param url - The URL to look up the cache key for
 * @returns The cache key or undefined if not found
 */
getCacheKeyForURL(url: string): string | undefined;

/**
 * Returns subresource integrity value for a cache key
 * @param cacheKey - The cache key to look up integrity for
 * @returns The integrity value or undefined if not found
 */
getIntegrityForCacheKey(cacheKey: string): string | undefined;

Usage Examples:

const controller = new PrecacheController();

// Check what's cached
const urlToCacheKey = controller.getURLsToCacheKeys();
console.log('Cached URLs:', Array.from(urlToCacheKey.keys()));

const cachedURLs = controller.getCachedURLs();
console.log('All cached URLs:', cachedURLs);

// Get cache key for specific URL
const cacheKey = controller.getCacheKeyForURL("/index.html");
if (cacheKey) {
  const integrity = controller.getIntegrityForCacheKey(cacheKey);
  console.log('Integrity for /index.html:', integrity);
}

Request Handling

Methods for matching and serving precached requests.

/**
 * Looks up a request in the precache
 * @param request - The key (URL string or Request object) to look up
 * @returns Promise resolving to cached response or undefined
 */
matchPrecache(request: string | Request): Promise<Response | undefined>;

/**
 * Creates a route handler bound to a specific precached URL
 * @param url - The precached URL to bind the handler to
 * @returns Route handler function
 */
createHandlerBoundToURL(url: string): RouteHandlerCallback;

Usage Examples:

const controller = new PrecacheController();

// Manual request matching
self.addEventListener('fetch', async (event) => {
  const cachedResponse = await controller.matchPrecache(event.request);
  if (cachedResponse) {
    event.respondWith(cachedResponse);
  }
});

// Create bound handler for routing
import { registerRoute } from "workbox-routing";

const handler = controller.createHandlerBoundToURL("/offline.html");
registerRoute(
  ({ request }) => request.mode === 'navigate',
  handler
);

Result Types

interface InstallResult {
  /** List of URLs that were updated during installation */
  updatedURLs: string[];
  
  /** List of URLs that were already up to date */
  notUpdatedURLs: string[];
}

interface CleanupResult {
  /** List of URLs that were deleted while cleaning up the cache */
  deletedCacheRequests: string[];
}

Error Handling

The following errors may be thrown by PrecacheController methods:

  • WorkboxError('add-to-cache-list-conflicting-entries') - When adding conflicting cache entries with different revisions for the same URL
  • WorkboxError('add-to-cache-list-conflicting-integrities') - When integrity values conflict for the same cache entry
  • WorkboxError('non-precached-url') - When createHandlerBoundToURL() is called with a URL that is not in the precache
## Advanced Usage Patterns

### Custom Cache Management

```typescript
import { PrecacheController } from "workbox-precaching";

class CustomPrecacheManager {
  private controller: PrecacheController;

  constructor() {
    this.controller = new PrecacheController({
      cacheName: "app-shell-v1",
      plugins: [
        {
          cacheWillUpdate: async ({ response }) => {
            // Only cache successful responses
            return response.status === 200 ? response : null;
          }
        }
      ]
    });
  }

  async initialize(manifest: Array<PrecacheEntry>) {
    this.controller.addToCacheList(manifest);
  }

  async handleInstall(event: ExtendableEvent) {
    const result = await this.controller.install(event);
    // Custom installation logic
    if (result.updatedURLs.length > 0) {
      // Notify about updates
      self.clients.claim();
    }
    return result;
  }

  isUrlPrecached(url: string): boolean {
    return this.controller.getCacheKeyForURL(url) !== undefined;
  }
}

Multiple Controllers

const appShellController = new PrecacheController({
  cacheName: "app-shell-v1"
});

const assetsController = new PrecacheController({
  cacheName: "static-assets-v1"
});

// Manage different types of assets separately
appShellController.precache([
  { url: "/", revision: "shell-v1" },
  { url: "/offline.html", revision: "offline-v1" }
]);

assetsController.precache([
  "/images/logo.png",
  "/fonts/main.woff2"
]);

Install with Tessl CLI

npx tessl i tessl/npm-workbox-precaching

docs

advanced-controller.md

index.md

plugins-cleanup.md

route-strategy.md

simple-setup.md

utilities.md

tile.json