googlecodelabs / your-first-pwapp

Code associated with Your First Progressive Web App codelab
https://g.co/codelabs/pwa
Apache License 2.0
638 stars 555 forks source link

Why only return cached "navigate" requests? #171

Open quinncomendant opened 5 years ago

quinncomendant commented 5 years ago

In the example for Handle failed network requests, the service worker is only handling requests that are "navigate" requests if (evt.request.mode !== 'navigate'):

// CODELAB: Add fetch event handler here.
if (evt.request.mode !== 'navigate') {
  // Not a page navigation, bail.
  return;
}
evt.respondWith(
    fetch(evt.request)
        .catch(() => {
          return caches.open(CACHE_NAME)
              .then((cache) => {
                return cache.match('offline.html');
              });
        })
);

This means requests for static assets like css and js are handled instead by normal browser requests, and will not be returned by the cache. If you intend to save some css or js files for offline use in the cache during the 'install' event, they will never be retrieved from the cache by the code above, and will result in broken pages.

What is the rationale behind skipping non-navigate requests? How do you expect the app to access cached "non-navigate" assets?

The only reason I can think of, would be so the offline.html file is only served for "navigate" requests, and never returned for a request for a css or image file. But the correct way to implement that would be to instead check the filetype of the request, and return a special offline file for each type of request, e.g., offline.html for navigate requests, and empty files matching the files for other request types: an empty offline.png for image requests, and offline.txt for text requests.