简体   繁体   中英

Service worker returns offline html page for javascript files

I'm new to service workers and offline capabilities. I created a simple service worker to handle network requests and return a offline html page when offline. This was created following Google's guide on PWA.

The problem is that the service worker returns offline.html when requesting javascript files (not cached). It should instead return a network error or something. Here is the code:

const cacheName = 'offline-v1900'; //increment version to update cache
// cache these files needed for offline use
const appShellFiles = [
    './offline.html',
    './css/bootstrap.min.css',
    './img/logo/logo.png',
    './js/jquery-3.5.1.min.js',
    './js/bootstrap.min.js',
];

self.addEventListener("fetch", (e) => {
  // We only want to call e.respondWith() if this is a navigation request
  // for an HTML page.
  // console.log(e.request.url);
  e.respondWith(
    (async () => {
      try {
        // First, try to use the navigation preload response if it's supported.
        const preloadResponse = await e.preloadResponse;
        if (preloadResponse) {
            // console.log('returning preload response');
          return preloadResponse;
        }

        const cachedResponse = await caches.match(e.request);
            if (cachedResponse) {
                // console.log(`[Service Worker] Fetching cached resource: ${e.request.url}`);
                return cachedResponse;
            }

        // Always try the network first.
        const networkResponse = await fetch(e.request);
        return networkResponse;
      } catch (error) {
        // catch is only triggered if an exception is thrown, which is likely
        // due to a network error.
        // If fetch() returns a valid HTTP response with a response code in
        // the 4xx or 5xx range, the catch() will NOT be called.

        // console.log("Fetch failed; returning offline page instead.", error);
        const cachedResponse = await caches.match('offline.html');
        return cachedResponse;
      }
    })()
  );

When offline, I open a url on my site, it loads the page from the cache but not all assets are cached for offline. So when a network request is made for, say https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js , the response I get is the html of offline.html page. This breaks the page because of javascript errors.

It should instead return a network error or something.

I think the relevant sample code is from https://googlechrome.github.io/samples/service-worker/custom-offline-page/

self.addEventListener('fetch', (event) => {
  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === 'navigate') {
    event.respondWith((async () => {
      try {
        // First, try to use the navigation preload response if it's supported.
        const preloadResponse = await event.preloadResponse;
        if (preloadResponse) {
          return preloadResponse;
        }

        const networkResponse = await fetch(event.request);
        return networkResponse;
      } catch (error) {
        // catch is only triggered if an exception is thrown, which is likely
        // due to a network error.
        // If fetch() returns a valid HTTP response with a response code in
        // the 4xx or 5xx range, the catch() will NOT be called.
        console.log('Fetch failed; returning offline page instead.', error);

        const cache = await caches.open(CACHE_NAME);
        const cachedResponse = await cache.match(OFFLINE_URL);
        return cachedResponse;
      }
    })());
  }

  // If our if() condition is false, then this fetch handler won't intercept the
  // request. If there are any other fetch handlers registered, they will get a
  // chance to call event.respondWith(). If no fetch handlers call
  // event.respondWith(), the request will be handled by the browser as if there
  // were no service worker involvement.
});

Specifically, that fetch handler checks to see whether event.request.mode === 'navigate' and only returns HTML when offline if that's the case. That's what's required to make sure that you don't end up returning offline HTML for other types of resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM