Workbox
repository·v7·Indexed 11 days ago
https://github.com/googlechrome/workboxA collection of JavaScript libraries for building Progressive Web Apps (PWAs), providing tools for service worker management, asset caching, and offline capabilities. Includes modules such as workbox-background-sync for deferring failed network requests and workbox-broadcast-update for notifying clients of cache updates.
What's inside Workbox
- Workbox is a collection of JavaScript libraries designed to help developers build Progressive Web Apps (PWAs). It provides a suite of tools and strategies for efficiently caching and serving web assets, managing service workers, and handling offline scenarios. Workbox simplifies the implementation of common caching patterns, allowing developers to build robust and resilient web applications.
Explore Workbox module demos
v7You can view live, deployed sample demonstrations of various Workbox modules on Glitch. These demos serve as practical examples for the modules documented at the official Workbox website.
Live Demos: https://glitch.com/@philkrie/workbox-demos
Official Documentation Reference: https://developers.google.com/web/tools/workbox/modules
Use caching strategies from workbox-strategies
v7The
workbox-strategiesmodule provides several common caching strategies for service workers. These strategies determine how the service worker handles network requests and cache interactions.Available strategies include:
CacheFirst: Attempts to serve the request from the cache first, falling back to the network if the cache is empty.CacheOnly: Serves the request only from the cache. If the resource is not in the cache, the request fails.NetworkFirst: Attempts to fetch the resource from the network first, falling back to the cache if the network request fails.NetworkOnly: Fetches the resource from the network only, without interacting with the cache.StaleWhileRevalidate: Serves the request from the cache immediately (if available) while simultaneously fetching an updated version from the network to update the cache for the next use.
import { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate } from 'workbox-strategies'; // Example usage with a router (conceptual): // registerRoute( // ({url}) => url.pathname.startsWith('/api/'), // new NetworkFirst() // );Use workbox-background-sync for background synchronization
v7The
workbox-background-syncmodule provides tools to defer failed network requests until the user has a stable internet connection. It uses the Background Sync API to retry requests in the background.Key components include:
BackgroundSyncPlugin: A plugin for Workbox strategies that manages the queuing and retrying of failed requests.Queue: A mechanism to store and manage requests that need to be retried.QueueOptions: Configuration for how the queue behaves (e.g., max attempts, expiration).QueueStore: The underlying storage mechanism for the queue.StorableRequest: A representation of a request that can be serialized and stored.
Use workbox-routing to manage service worker requests
v7The
workbox-routingpackage provides the core routing mechanisms for Workbox. It allows you to intercept network requests and map them to specific handlers based on URL patterns, request methods, or other criteria.Key components include:
registerRoute: The primary way to define a route and its associated handler.Route: A base class for defining custom routing logic.RegExpRoute: A specialized route that matches requests using regular expressions.NavigationRoute: A specialized route designed to handle navigation requests (e.g., when a user enters a URL in the browser).Router: A mechanism to manage and execute multiple routes.setCatchHandler: Defines a fallback handler for when all other routes fail to match.setDefaultHandler: Defines a handler that is used when no other routes match.
Use workbox-core for shared utilities and defaults
v7Theworkbox-corepackage serves as the foundation for all other Workbox service worker libraries. It provides shared utilities, default values (such as cache names), and essential service worker lifecycle management functions. You will typically useworkbox-coreindirectly when using other Workbox modules, but you can import it directly for low-level operations.Use workbox-broadcast-update to notify clients of cache updates
v7The
workbox-broadcast-updatepackage provides tools to notify multiple browser tabs (clients) when a specific cache has been updated. This is useful for ensuring that all open instances of your application stay in sync when data changes in the background.Key components include:
BroadcastUpdatePlugin: A plugin for Workbox strategies that automatically broadcasts a message when a response is cached.BroadcastCacheUpdate: A utility to manually broadcast cache update messages.responsesAreSame: A utility function to determine if two responses are identical, which can be used to decide whether a broadcast is necessary.
Use workbox-build to generate or inject service workers
v7The
workbox-buildpackage provides tools for automating the creation of service workers during your build process. It offers two primary workflows:generateSW: Generates a new service worker file from scratch based on a configuration object. This is ideal for simple use cases where you don't need custom service worker logic.injectManifest: Takes an existing service worker file (a 'template') and injects a manifest of precached assets into it. This is required if you want to write custom service worker code (e.g., custom event listeners or complex routing logic).
Other utilities include
getManifestfor retrieving a list of files to precache andcopyWorkboxLibrariesfor local deployment of Workbox modules.Use workbox-streams to manipulate response streams
v7The
workbox-streamspackage provides utilities for manipulating response streams, which is useful for advanced service worker scenarios like combining multiple responses or streaming content.Key functions include:
concatenate: Combines multipleReadableStreamobjects into a single stream.concatenateToResponse: Combines multipleResponseobjects into a singleResponseobject.isSupported: Checks if the current environment supports the necessary streaming APIs.strategy: A higher-order function used to create a streaming strategy for handling requests.
Use Workbox Recipes for common caching patterns
v7The
workbox-recipespackage provides pre-configured, high-level functions (recipes) to implement common Service Worker caching strategies and patterns. Instead of manually configuring routes and strategies, you can use these recipes to quickly implement features like image caching, Google Fonts caching, or offline fallbacks.Available recipes include:
googleFontsCache: Caches Google Fonts.imageCache: Caches images.staticResourceCache: Caches static resources.pageCache: Caches pages.offlineFallback: Provides an offline fallback for navigation requests.warmStrategyCache: Pre-caches resources using a specific strategy.
Advanced precaching with PrecacheController
v7IfprecacheAndRoutedoes not provide enough control over how assets are cached or how requests are routed, you can use thePrecacheControllerinterface. This allows for more granular management of the precaching lifecycle and routing logic.How routing match and handler callbacks work together
v7Workbox routing relies on two distinct callback stages: matching and handling.
RouteMatchCallback: This function determines if aRouteapplies to a specific URL or request. If it returns a truthy value, the route matches. If it returns a non-empty array or object, that value is passed to the handler asparams.RouteHandlerCallback: Once a match is confirmed, this callback is invoked. It must return aPromisethat resolves with aResponse.
Note that
RouteMatchCallbackmay be called outside of a fetch event, so logic should not strictly depend on theeventobject being present./** * Example conceptual flow: * * const matchCallback = (options) => { * if (options.url.pathname.startsWith('/api/')) { * return { type: 'api', version: 'v1' }; // This becomes 'params' * } * return false; * }; * * const handlerCallback = async (options) => { * const { params, request } = options; * // params is { type: 'api', version: 'v1' } * return fetch(request); * }; */