StaleWhileRevalidate extends module:workbox-runtime-caching.Handler

An implementation of a stale-while-revalidate request strategy.

Resources are requested from both the cache and the network in parallel, then responds with the cached version. The cache is replaced with whatever returns from the network. In addition to updating the appropriate caches, it will also trigger any appropriate plugins defined in the underlying RequestWrapper.

By default, StaleWhileRevalidate will cache responses with a 200 status code as well as opaque responses (responses from cross-origin servers which don't support CORS). You can override this default by passing in a RequestWrapper that includes an appropriately-configured CacheableResponsePlugin.

Example

// Set up a route to match any requests made for URLs that end in .txt.
// The requests are handled with a stale-while-revalidate strategy.
const route = new workbox.routing.RegExpRoute({
  regExp: /\.txt$/,
  handler: new workbox.runtimeCaching.StaleWhileRevalidate(),
});

const router = new workbox.routing.Router();
router.registerRoute({route});

Constructor

new StaleWhileRevalidate(input)

Constructor for a new StaleWhileRevalidate instance.

Parameters
input Object
Properties
requestWrapper RequestWrapper (Optional)

An optional RequestWrapper that is used to configure the cache name and request plugins. If not provided, a new RequestWrapper using the default cache name will be used.

Instance Methods

this.handle(input) Promise.<Response>

The handle method will be called by the Route class when a route matches a request.

Parameters
input Object
Properties
event FetchEvent

The event that triggered the service worker's fetch handler.

Returns Promise.<Response>

The response from the cache, if present, or from the network if not.