How to use workbox-strategies - 10 common examples

To help you get started, we’ve selected a few workbox-strategies examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ampproject / amp-sw / src / modules / amp-caching / index.ts View on Github external
ampAssetsCaching() {
    // Versioned Assets
    router.registerRoute(
      VERSIONED_ASSETS_RE,
      new CacheFirst({
        cacheName: VERSIONED_CACHE_NAME,
        plugins: [
          new Plugin({
            maxAgeSeconds: 14 * 24 * 60 * 60, // 14 days
          }),
        ],
      }),
    );

    // Unversioned runtimes
    router.registerRoute(
      UNVERSIONED_RUNTIME_RE,
      new StaleWhileRevalidate({
        cacheName: UNVERSIONED_CACHE_NAME,
        plugins: [
          new Plugin({
github go-gitea / gitea / web_src / js / serviceworker.js View on Github external
self.__WB_DISABLE_DEV_LOGS = true;

// see https://developer.mozilla.org/en-US/docs/Web/API/RequestDestination for possible values
const cachedDestinations = new Set([
  'font',
  'manifest',
  'paintworklet',
  'script',
  'sharedworker',
  'style',
  'worker',
]);

registerRoute(
  ({request}) => cachedDestinations.has(request.destination),
  new StaleWhileRevalidate({cacheName}),
);
github ampproject / amp-sw / src / modules / amp-caching / index.ts View on Github external
router.registerRoute(
      UNVERSIONED_RUNTIME_RE,
      new StaleWhileRevalidate({
        cacheName: UNVERSIONED_CACHE_NAME,
        plugins: [
          new Plugin({
            maxAgeSeconds: 7 * 24 * 60 * 60, // 7 days
          }),
        ],
      }),
    );

    // Unversioned Extensions
    router.registerRoute(
      UNVERSIONED_EXTENSIONS_RE,
      new StaleWhileRevalidate({
        cacheName: UNVERSIONED_CACHE_NAME,
        plugins: [
          new Plugin({
            maxAgeSeconds: 24 * 60 * 60, // 1 day
          }),
        ],
      }),
    );
  }
github philipwalton / blog / assets / sw / precache.js View on Github external
/* global __PRECACHE_MANIFEST__ */

import {PrecacheController} from 'workbox-precaching/PrecacheController.mjs';
import {Route} from 'workbox-routing/Route.mjs';
import {CacheFirst} from 'workbox-strategies/CacheFirst.mjs';
import {cacheNames} from './caches.js';


const pc = new PrecacheController(cacheNames.SHELL);

const precacheMatcher = ({url}) => {
  return Boolean(pc.getCacheKeyForURL(url.href));
};

const cacheFirst = new CacheFirst({cacheName: cacheNames.SHELL});

export const precacheHandler = ({request, event}) => {
  const cacheKey = pc.getCacheKeyForURL(request.url);

  return cacheFirst.handle({
    request: new Request(cacheKey),
    event,
  });
};

export const createPrecacheRoute = () => {
  return new Route(precacheMatcher, precacheHandler);
};

export const install = (opts) => pc.install(opts);
export const activate = (opts) => pc.activate(opts);
github philipwalton / blog / assets / sw / routes / content.js View on Github external
const addCacheHeadersPlugin = {
  // Add the `X-Cache-Date` header for requests going to the cache
  async cacheWillUpdate({response}) {
    return copyResponse(response, (responseInit) => {
      responseInit.headers.set('X-Cache-Date', new Date().toUTCString());
      return responseInit;
    });
  },
};

const contentMatcher = ({url}) => {
  return url.hostname === location.hostname &&
      url.pathname.endsWith('index.content.html');
};

export const contentStrategy = new StaleWhileRevalidate({
  cacheName: cacheNames.CONTENT,
  plugins: [
    addCacheHeadersPlugin,
    broadcastUpdatePlugin,
    navigationReportPlugin,
  ],
});

export const createContentRoute = () => {
  return new Route(contentMatcher, contentStrategy);
};
github philipwalton / blog / assets / sw / routes / third-party-assets.js View on Github external
import {Route} from 'workbox-routing/Route.mjs';
import {StaleWhileRevalidate} from 'workbox-strategies/StaleWhileRevalidate.mjs';
import {cacheNames} from '../caches.js';

const thirdPartyAssetsMatcher = ({url}) => {
  return url.hostname !== location.hostname &&
      // Just match .js now, consider adding images and stuff later,
      // but we probably don't need to be caching videos.
      url.pathname.match(/\.(?:js)$/);
};

const thirdPartyAssetsStrategy = new StaleWhileRevalidate({
  cacheName: cacheNames.THIRD_PARTY_ASSETS,
});

export const createThirdPartyAssetsRoute = () => {
  return new Route(thirdPartyAssetsMatcher, thirdPartyAssetsStrategy);
};
github GoogleChrome / samples / web-share / src / js / service-worker.js View on Github external
}

  // Use the MIME type of the first file shared to determine where we redirect.
  const routeToRedirectTo = [
    audioRoute,
    imagesRoute,
    videosRoute,
  ].find((route) => mediaFiles[0].type.startsWith(route.mimePrefix));

  const redirectionUrl = routeToRedirectTo ? `/#${routeToRedirectTo.href}` : '/';
  
  // After the POST succeeds, redirect to the main page.
  return Response.redirect(redirectionUrl, 303);
};

const cachedMediaHandler = new CacheOnly({
  cacheName,
  plugins: [
    // Support for cache requests that include a Range: header.
    new RangeRequestsPlugin(),
  ],
});

skipWaiting();
clientsClaim();

// This will be replaced by the list of files to precache by
// the `workbox injectManifest` build step.
precacheAndRoute(self.__WB_MANIFEST);

registerRoute(
  '/_share-target',
github philipwalton / blog / assets / sw / routes / shell.js View on Github external
* Given an asset URL that we already know to be in `/static/`, return true
 * if this assets is part of the application shell.
 * @param {string} pathname
 * @return {boolean}
 */
export const isShellAsset = (pathname) => {
  return /(html|css|mjs)$/.test(pathname);
};

const shellMatcher = ({url}) => {
  return url.hostname === location.hostname &&
      url.pathname.startsWith('/static/') &&
      isShellAsset(url.pathname);
};

export const shellStrategy = new CacheFirst({
  cacheName: cacheNames.SHELL,
});

export const createShellRoute = () => {
  return new Route(shellMatcher, shellStrategy);
};
github GoogleChrome / workbox / packages / workbox-google-analytics / src / initialize.ts View on Github external
const createCollectRoutes = (bgSyncPlugin: BackgroundSyncPlugin) => {
  const match = ({url}: RouteMatchCallbackOptions) =>
      url.hostname === GOOGLE_ANALYTICS_HOST &&
      COLLECT_PATHS_REGEX.test(url.pathname);

  const handler = new NetworkOnly({
    plugins: [bgSyncPlugin],
  });

  return [
    new Route(match, handler, 'GET'),
    new Route(match, handler, 'POST'),
  ];
};
github ampproject / amp-sw / src / modules / link-prefetch / index.ts View on Github external
linksRegExps.forEach(link => {
      navigationRoute_.addDeniedUrls(link);
      router.registerRoute(
        link,
        new CacheFirst({
          cacheName: AMP_PREFETCHED_LINKS,
          plugins: [
            new AmpPrefetchPlugin({
              maxEntries: 10,
              maxAgeSeconds: maxAgeSecondsInCache,
              postDelete: (url: string) => {
                const linkRE = convertUrlToRegExp(cleanHostInfoFromUrl(url));
                navigationRoute_.removeDeniedUrls(linkRE);
              },
            }),
          ],
          networkTimeoutSeconds: 0.5,
        }),
      );
    });
  }