kikidoyouloveme
kikidoyouloveme

Reputation: 55

Service worker goes to redudent phase because pre-caching files are blocked by Ad Blocker(a chrome extension.)

All the logic get failed because chrome extensions block one of my js files, Is there a way to make pre-caching more robust? even if I get an error when caching some files, I can still cache most of them correctly, and I have run time caching.

Upvotes: 0

Views: 238

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

If you're using workbox-precaching, then the answer is no—it's designed so that service worker installation will only proceed if all of the items in the precache manifest were successfully added to the cache. That way, you're guaranteed to have a functional set of resources available offline. (There's a longstanding feature request for adding support for "optional" precaching, but it's not clear how that would work in practice.)

I'd recommend using runtime caching for URLs that are optional, and might be blocked by browser extensions. If you want to "warm" the cache in this scenario, and you don't care if the cache population fails, you can add your own logic along the lines of:

import {CacheFirst} from 'workbox-strategies';
import {registerRoute} from 'workbox-routing';
import {precacheAndRoute} from 'workbox-precaching';

const OPTIONAL_CACHE_NAME = 'optional-resources';
const OPTIONAL_URLS = [
  // Add URLs here that might be blocked.
];

self.addEventListener('install', (event) => {
  event.waitUntil((async () => {
    const cache = await caches.open(RUNTIME_CACHE_NAME);
    for (const url of OPTIONAL_URLS) {
      try {
        await cache.add(url);
      } catch (e) {
        // Ignore failures due to, e.g., a content blocker.
      }
    }
  })());
});

// Precache everything in the manifest, which you need to
// configure to exclude your "optional" URLs.
precacheAndRoute(self.__WB_MANIFEST);

// Use a cache-first runtime strategy.
registerRoute(
  // Check url.pathname, or url.href, if OPTIONAL_URLS
  // contains full URLs.
  ({url}) => OPTIONAL_URLS.includes(url.pathname),
  new CacheFirst({cacheName: OPTIONAL_CACHE_NAME}),
);

Upvotes: 2

Related Questions