服务人员-首先通过网络进行缓存,然后回退到静态页面 [英] Service worker - network first then cache with fallback to static page

查看:54
本文介绍了服务人员-首先通过网络进行缓存,然后回退到静态页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将服务人员添加到我的网站,以便为我的网站用户提供良好的脱机体验.(网站后端是PHP)

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

我对Javascript Promise和服务人员仍然不陌生,但这是我到目前为止所达到的目标:

I'm still new to Javascript promises and service workers, but here is what i reached so far :

我的 index.php 页面具有用于注册服务人员的脚本

my index.php page has this script to register service worker

<script> 
    if ('serviceWorker' in navigator) { navigator.serviceWorker.register('sw.js')};
</script>

,对于服务人员文件,我使用以下代码

var CACHE_STATIC_NAME = 'static-v74';
var CACHE_DYNAMIC_NAME = 'dynamic-v74';

self.addEventListener('install', function (event) {
  console.log('Installing Service Worker ...', event);
  event.waitUntil(
    caches.open(CACHE_STATIC_NAME)
      .then(function (cache) {
        console.log('Precaching App Shell');
        cache.addAll([
          'offline.php', // offline page
          'assets/bundle.css',
          'assets/bundle.js',
          'assets/images/logo.jpg',
          'assets/images/favicon.ico'
        ]);
      })
  )
});

self.addEventListener('activate', function (event) {
  console.log('Activating Service Worker ....', event);
  event.waitUntil(
    caches.keys()
      .then(function (keyList) {
        return Promise.all(keyList.map(function (key) {
          if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
            console.log('Removing old cache.', key);
            return caches.delete(key);
          }
        }));
      })
  );
  return self.clients.claim();
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    // Try the network
    fetch(event.request)
      .then(function(res) {
        return caches.open(CACHE_DYNAMIC_NAME)
          .then(function(cache) {
            // Put in cache if succeeds
            cache.put(event.request.url, res.clone());
            return res;
          })
      })
      .catch(function(err) {
          // Fallback to cache
          return caches.match(event.request);
      })
  );
});

实际上,此代码按预期工作正常:

in fact this code is working fine as expected :

(1)注册服务人员&复制我的静态缓存文件.(2)激活新的服务工作者时,它将删除旧的缓存.(3)每次收到新请求时,都会先从网络中获取&如果成功,则将请求的新副本放入缓存中.(4)如果离线时无法发出网络请求,则会向用户返回上一次网络请求的新副本.

(1) It registers the service worker & take copy of my static cache files. (2) When activating a new service worker it removes the old cache. (3) With every new request it fetches from network first & if succeeded it puts a fresh copy of request in cache. (4) If failed to make network request when offline it gives back the user a fresh copy of last network request.

我想实现的目标是(如果-用户处于离线状态-并尝试请求不在缓存中的新页面,则应将他重定向到保存在静态页面中的(offline.php)页面)缓存)如下所示

what i want to achieve her is (in case - user is offline - and try to request a new page that isn't in cache, he should be redirected to the (offline.php) page which was saved in the static cache) like the following

// If both (network & cache) fail, show a generic fallback:
return caches.match('offline.php');

但是我有一个问题,我不知道在(提取)步骤中我的(sw.js)文件中应该确切地添加此行,我确实尝试阅读有关服务工作者的详细信息&Javascript承诺并尝试将这行代码添加到我的代码中不同的位置几次,但是每次都行不通,却错过了上一个方案或保留该方案,但未能实现此目标.

but i have a problem that i don't know where exactly should i add this line in my (sw.js) file within (fetch) step, i really tried reading more about service workers & Javascript promises and tried adding this line several times different place in my code, but every time neither make it work but misses up with the previous scenario or keep the scenario but fail to achieve this goal.

非常感谢您的帮助&预先感谢.

Really appreciate your kind help & many thanks in advance.

推荐答案

在您的提取事件监听器中:

In your fetch event listener:

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

实际上,

caches.match(event.request)返回一个Promise,如果未从缓存中找到匹配项,则该Promise解析为undefined.

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

检查未定义并从缓存中返回offline.php:

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;
})

这篇关于服务人员-首先通过网络进行缓存,然后回退到静态页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆