workbox-strategies
Summary
- Types
Types
CacheFirst
An implementation of a cache-first request strategy.
A cache first strategy is useful for assets that have been revisioned, such as URLs like /styles/example.a8f5f1.css, since they can be cached for long periods of time.
If the network request fails, and there is no cache match, this will throw a WorkboxError exception.
Properties
- constructor
function
Creates a new instance of the strategy and sets all documented option properties as public instance properties.
Note: if a custom strategy class extends the base Strategy class and does not need more than these properties, it does not need to define its own constructor.
The
constructorfunction looks like:(options?: StrategyOptions) => {...}- options
StrategyOptions optional
- returns
- cacheName
string
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- plugins
- _awaitComplete
function
The
_awaitCompletefunction looks like:(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- responseDone
Promise<Response>
- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<void>
- _getResponse
function
The
_getResponsefunction looks like:(handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<Response>
- handle
function
Perform a request strategy and returns a
Promisethat will resolve with aResponse, invoking all relevant plugin callbacks.When a strategy instance is registered with a Workbox
workbox-routing.Route, this method is automatically called when the route matches.Alternatively, this method can be used in a standalone
FetchEventlistener by passing it toevent.respondWith().The
handlefunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
Promise<Response>
- handleAll
function
Similar to
workbox-strategies.Strategy~handle, but instead of just returning aPromisethat resolves to aResponseit it will return an tuple of[response, done]promises, where the former (response) is equivalent to whathandle()returns, and the latter is a Promise that will resolve once any promises that were added toevent.waitUntil()as part of performing the strategy have completed.You can await the
donepromise to ensure any extra work performed by the strategy (usually caching responses) completes successfully.The
handleAllfunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
[Promise<Response>, Promise<void>]
A tuple of [response, done] promises that can be used to determine when the response resolves as well as when the handler has completed all its work.
CacheOnly
An implementation of a cache-only request strategy.
This class is useful if you want to take advantage of any Workbox plugins.
If there is no cache match, this will throw a WorkboxError exception.
Properties
- constructor
function
Creates a new instance of the strategy and sets all documented option properties as public instance properties.
Note: if a custom strategy class extends the base Strategy class and does not need more than these properties, it does not need to define its own constructor.
The
constructorfunction looks like:(options?: StrategyOptions) => {...}- options
StrategyOptions optional
- returns
- cacheName
string
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- plugins
- _awaitComplete
function
The
_awaitCompletefunction looks like:(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- responseDone
Promise<Response>
- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<void>
- _getResponse
function
The
_getResponsefunction looks like:(handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<Response>
- handle
function
Perform a request strategy and returns a
Promisethat will resolve with aResponse, invoking all relevant plugin callbacks.When a strategy instance is registered with a Workbox
workbox-routing.Route, this method is automatically called when the route matches.Alternatively, this method can be used in a standalone
FetchEventlistener by passing it toevent.respondWith().The
handlefunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
Promise<Response>
- handleAll
function
Similar to
workbox-strategies.Strategy~handle, but instead of just returning aPromisethat resolves to aResponseit it will return an tuple of[response, done]promises, where the former (response) is equivalent to whathandle()returns, and the latter is a Promise that will resolve once any promises that were added toevent.waitUntil()as part of performing the strategy have completed.You can await the
donepromise to ensure any extra work performed by the strategy (usually caching responses) completes successfully.The
handleAllfunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
[Promise<Response>, Promise<void>]
A tuple of [response, done] promises that can be used to determine when the response resolves as well as when the handler has completed all its work.
NetworkFirst
An implementation of a network first request strategy.
By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests where the response doesn't support CORS.
If the network request fails, and there is no cache match, this will throw a WorkboxError exception.
Properties
- constructor
function
The
constructorfunction looks like:(options?: NetworkFirstOptions) => {...}- options
NetworkFirstOptions optional
- returns
- cacheName
string
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- plugins
- _awaitComplete
function
The
_awaitCompletefunction looks like:(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- responseDone
Promise<Response>
- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<void>
- _getResponse
function
The
_getResponsefunction looks like:(handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<Response>
- handle
function
Perform a request strategy and returns a
Promisethat will resolve with aResponse, invoking all relevant plugin callbacks.When a strategy instance is registered with a Workbox
workbox-routing.Route, this method is automatically called when the route matches.Alternatively, this method can be used in a standalone
FetchEventlistener by passing it toevent.respondWith().The
handlefunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
Promise<Response>
- handleAll
function
Similar to
workbox-strategies.Strategy~handle, but instead of just returning aPromisethat resolves to aResponseit it will return an tuple of[response, done]promises, where the former (response) is equivalent to whathandle()returns, and the latter is a Promise that will resolve once any promises that were added toevent.waitUntil()as part of performing the strategy have completed.You can await the
donepromise to ensure any extra work performed by the strategy (usually caching responses) completes successfully.The
handleAllfunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
[Promise<Response>, Promise<void>]
A tuple of [response, done] promises that can be used to determine when the response resolves as well as when the handler has completed all its work.
NetworkFirstOptions
Properties
- cacheName
string optional
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- networkTimeoutSeconds
number optional
- plugins
WorkboxPlugin[] optional
NetworkOnly
An implementation of a network-only request strategy.
This class is useful if you want to take advantage of any Workbox plugins.
If the network request fails, this will throw a WorkboxError exception.
Properties
- constructor
function
The
constructorfunction looks like:(options?: NetworkOnlyOptions) => {...}- options
NetworkOnlyOptions optional
- returns
- cacheName
string
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- plugins
- _awaitComplete
function
The
_awaitCompletefunction looks like:(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- responseDone
Promise<Response>
- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<void>
- _getResponse
function
The
_getResponsefunction looks like:(handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<Response>
- handle
function
Perform a request strategy and returns a
Promisethat will resolve with aResponse, invoking all relevant plugin callbacks.When a strategy instance is registered with a Workbox
workbox-routing.Route, this method is automatically called when the route matches.Alternatively, this method can be used in a standalone
FetchEventlistener by passing it toevent.respondWith().The
handlefunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
Promise<Response>
- handleAll
function
Similar to
workbox-strategies.Strategy~handle, but instead of just returning aPromisethat resolves to aResponseit it will return an tuple of[response, done]promises, where the former (response) is equivalent to whathandle()returns, and the latter is a Promise that will resolve once any promises that were added toevent.waitUntil()as part of performing the strategy have completed.You can await the
donepromise to ensure any extra work performed by the strategy (usually caching responses) completes successfully.The
handleAllfunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
[Promise<Response>, Promise<void>]
A tuple of [response, done] promises that can be used to determine when the response resolves as well as when the handler has completed all its work.
NetworkOnlyOptions
Properties
- fetchOptions
RequestInit optional
- networkTimeoutSeconds
number optional
- plugins
WorkboxPlugin[] optional
StaleWhileRevalidate
An implementation of a stale-while-revalidate request strategy.
Resources are requested from both the cache and the network in parallel. The strategy will respond with the cached version if available, otherwise wait for the network response. The cache is updated with the network response with each successful request.
By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are cross-origin requests where the response doesn't support CORS.
If the network request fails, and there is no cache match, this will throw a WorkboxError exception.
Properties
- constructor
function
The
constructorfunction looks like:(options?: StrategyOptions) => {...}- options
StrategyOptions optional
- returns
- cacheName
string
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- plugins
- _awaitComplete
function
The
_awaitCompletefunction looks like:(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- responseDone
Promise<Response>
- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<void>
- _getResponse
function
The
_getResponsefunction looks like:(handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<Response>
- handle
function
Perform a request strategy and returns a
Promisethat will resolve with aResponse, invoking all relevant plugin callbacks.When a strategy instance is registered with a Workbox
workbox-routing.Route, this method is automatically called when the route matches.Alternatively, this method can be used in a standalone
FetchEventlistener by passing it toevent.respondWith().The
handlefunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
Promise<Response>
- handleAll
function
Similar to
workbox-strategies.Strategy~handle, but instead of just returning aPromisethat resolves to aResponseit it will return an tuple of[response, done]promises, where the former (response) is equivalent to whathandle()returns, and the latter is a Promise that will resolve once any promises that were added toevent.waitUntil()as part of performing the strategy have completed.You can await the
donepromise to ensure any extra work performed by the strategy (usually caching responses) completes successfully.The
handleAllfunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
[Promise<Response>, Promise<void>]
A tuple of [response, done] promises that can be used to determine when the response resolves as well as when the handler has completed all its work.
Strategy
An abstract base class that all other strategy classes must extend from:
Properties
- constructor
function
Creates a new instance of the strategy and sets all documented option properties as public instance properties.
Note: if a custom strategy class extends the base Strategy class and does not need more than these properties, it does not need to define its own constructor.
The
constructorfunction looks like:(options?: StrategyOptions) => {...}- options
StrategyOptions optional
- returns
- cacheName
string
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- plugins
- _awaitComplete
function
The
_awaitCompletefunction looks like:(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- responseDone
Promise<Response>
- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<void>
- _getResponse
function
The
_getResponsefunction looks like:(handler: StrategyHandler, request: Request, event: ExtendableEvent) => {...}- handler
- request
Request
- event
ExtendableEvent
- returns
Promise<Response>
- _handle
function
The
_handlefunction looks like:(request: Request, handler: StrategyHandler) => {...}- request
Request
- handler
- returns
Promise<Response>
- handle
function
Perform a request strategy and returns a
Promisethat will resolve with aResponse, invoking all relevant plugin callbacks.When a strategy instance is registered with a Workbox
workbox-routing.Route, this method is automatically called when the route matches.Alternatively, this method can be used in a standalone
FetchEventlistener by passing it toevent.respondWith().The
handlefunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
Promise<Response>
- handleAll
function
Similar to
workbox-strategies.Strategy~handle, but instead of just returning aPromisethat resolves to aResponseit it will return an tuple of[response, done]promises, where the former (response) is equivalent to whathandle()returns, and the latter is a Promise that will resolve once any promises that were added toevent.waitUntil()as part of performing the strategy have completed.You can await the
donepromise to ensure any extra work performed by the strategy (usually caching responses) completes successfully.The
handleAllfunction looks like:(options: FetchEvent | HandlerCallbackOptions) => {...}- options
FetchEvent | HandlerCallbackOptions
A
FetchEventor an object with the properties listed below.
- returns
[Promise<Response>, Promise<void>]
A tuple of [response, done] promises that can be used to determine when the response resolves as well as when the handler has completed all its work.
StrategyHandler
A class created every time a Strategy instance instance calls workbox-strategies.Strategy~handle or workbox-strategies.Strategy~handleAll that wraps all fetch and cache actions around plugin callbacks and keeps track of when the strategy is "done" (i.e. all added event.waitUntil() promises have resolved).
Properties
- constructor
function
Creates a new instance associated with the passed strategy and event that's handling the request.
The constructor also initializes the state that will be passed to each of the plugins handling this request.
The
constructorfunction looks like:(strategy: Strategy, options: HandlerCallbackOptions) => {...}- strategy
- options
- returns
- event
ExtendableEvent
- params
any optional
- request
Request
- url
URL optional
- cacheMatch
function
Matches a request from the cache (and invokes any applicable plugin callback methods) using the
cacheName,matchOptions, andpluginsdefined on the strategy object.The following plugin lifecycle methods are invoked when using this method:
- cacheKeyWillByUsed()
- cachedResponseWillByUsed()
The
cacheMatchfunction looks like:(key: RequestInfo) => {...}- key
RequestInfo
The Request or URL to use as the cache key.
- returns
Promise<Response>
A matching response, if found.
- cachePut
function
Puts a request/response pair in the cache (and invokes any applicable plugin callback methods) using the
cacheNameandpluginsdefined on the strategy object.The following plugin lifecycle methods are invoked when using this method:
- cacheKeyWillByUsed()
- cacheWillUpdate()
- cacheDidUpdate()
The
cachePutfunction looks like:(key: RequestInfo, response: Response) => {...}- key
RequestInfo
The request or URL to use as the cache key.
- response
Response
The response to cache.
- returns
Promise<boolean>
falseif a cacheWillUpdate caused the response not be cached, andtrueotherwise.
- destroy
function
Stops running the strategy and immediately resolves any pending
waitUntil()promises.The
destroyfunction looks like:() => {...} - doneWaiting
function
Returns a promise that resolves once all promises passed to
workbox-strategies.StrategyHandler~waitUntilhave settled.Note: any work done after
doneWaiting()settles should be manually passed to an event'swaitUntil()method (not this handler'swaitUntil()method), otherwise the service worker thread my be killed prior to your work completing.The
doneWaitingfunction looks like:() => {...}- returns
Promise<void>
- fetch
function
Fetches a given request (and invokes any applicable plugin callback methods) using the
fetchOptions(for non-navigation requests) andpluginsdefined on theStrategyobject.The following plugin lifecycle methods are invoked when using this method:
requestWillFetch()fetchDidSucceed()fetchDidFail()
The
fetchfunction looks like:(input: RequestInfo) => {...}- input
RequestInfo
The URL or request to fetch.
- returns
Promise<Response>
- fetchAndCachePut
function
Calls
this.fetch()and (in the background) runsthis.cachePut()on the response generated bythis.fetch().The call to
this.cachePut()automatically invokesthis.waitUntil(), so you do not have to manually callwaitUntil()on the event.The
fetchAndCachePutfunction looks like:(input: RequestInfo) => {...}- input
RequestInfo
The request or URL to fetch and cache.
- returns
Promise<Response>
- getCacheKey
function
Checks the list of plugins for the
cacheKeyWillBeUsedcallback, and executes any of those callbacks found in sequence. The finalRequestobject returned by the last plugin is treated as the cache key for cache reads and/or writes. If nocacheKeyWillBeUsedplugin callbacks have been registered, the passed request is returned unmodifiedThe
getCacheKeyfunction looks like:(request: Request, mode: "read" | "write") => {...}- request
Request
- mode
"read" | "write"
- returns
Promise<Request>
- hasCallback
function
Returns true if the strategy has at least one plugin with the given callback.
The
hasCallbackfunction looks like:(name: C) => {...}- name
C
The name of the callback to check for.
- returns
boolean
- iterateCallbacks
function
Accepts a callback and returns an iterable of matching plugin callbacks, where each callback is wrapped with the current handler state (i.e. when you call each callback, whatever object parameter you pass it will be merged with the plugin's current state).
The
iterateCallbacksfunction looks like:(name: C) => {...}- name
C
The name fo the callback to run
- returns
Generator<NonNullable<indexedAccess>anyunknown>
- runCallbacks
function
Runs all plugin callbacks matching the given name, in order, passing the given param object (merged ith the current plugin state) as the only argument.
Note: since this method runs all plugins, it's not suitable for cases where the return value of a callback needs to be applied prior to calling the next callback. See
workbox-strategies.StrategyHandler#iterateCallbacksbelow for how to handle that case.The
runCallbacksfunction looks like:(name: C, param: Omit<indexedAccess"state">) => {...}- name
C
The name of the callback to run within each plugin.
- param
Omit<indexedAccess"state">
The object to pass as the first (and only) param when executing each callback. This object will be merged with the current plugin state prior to callback execution.
- returns
Promise<void>
- waitUntil
function
Adds a promise to the [extend lifetime promises]
https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promisesof the event event associated with the request being handled (usually aFetchEvent).Note: you can await
workbox-strategies.StrategyHandler~doneWaitingto know when all added promises have settled.The
waitUntilfunction looks like:(promise: Promise<T>) => {...}- promise
Promise<T>
A promise to add to the extend lifetime promises of the event that triggered the request.
- returns
Promise<T>
StrategyOptions
Properties
- cacheName
string optional
- fetchOptions
RequestInit optional
- matchOptions
CacheQueryOptions optional
- plugins
WorkboxPlugin[] optional