Service worker - network first then cache with fallback to static page

前端 未结 1 500
暗喜
暗喜 2021-01-18 08:07

I want to add service worker to my site to offer a good offline experience to my site users. (Site back-end is PHP)

I\'m still new to Javascript promises and service

相关标签:
1条回答
  • 2021-01-18 08:39

    In your fetch event listener:

    .catch(function(err) {
          // Fallback to cache
          return caches.match(event.request);
      })
    

    caches.match(event.request) in fact returns a Promise that resolves to undefined if no match is found from the cache.

    Check for undefined and return offline.php from cache:

    return caches.match(event.request)
      .then(function(res){
        if (res === undefined) { 
          // get and return the offline page
        } 
        return res;
    })
    
    0 讨论(0)
提交回复
热议问题