Search code examples
javascriptdynamicfetchprogressive-web-apps

How to do a Fetch in a dynamic web page


So,

I'm developping a PWA, however i'm working on a dynamic app (one page). That mean that when i try to do a addEventListener(fetch) with my service workers, nothing returns. I tryed to do manual fetch like fetching my localhost etc... it worked well but i cant access to the fetch.request ! So i dont really know how to do an offline part to my app if i cant access to my cache's data with a fetch.

here is what i already tryed but it doesnt received any fetchs events :

this.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).catch(function() {
      return fetch(event.request).then(function(response) {
        return caches.open('v2').then(function(cache) {
          cache.put(event.request, response.clone());
          return response;
        });
      });
    })
  );
});

Any Ideas ?


Solution

  • If you want to follow the App Shell/single-page app routing model in your fetch handler, the best way to do that is to check to see if event.request.mode === 'navigate' inside of your fetch handler. If it is, that means that the user has navigated to some URL, and presumably you already have a one-size-fits-all-URLs shell.html cached that can be used to satisfy that navigation request.

    this.addEventListener('fetch', function(event) {
      if (event.request.mode === 'navigate') {
        // This assumes that shell.html was already cached,
        // e.g. as part of your `install` handler.
        event.respondWith(caches.match('shell.html'));
        return;
      }
    
      // Your other response/caching logic goes here.
    });