【问题标题】:How does the JavaScript ofline serviceworker example work?JavaScript 离线 serviceworker 示例是如何工作的?
【发布时间】:2020-03-20 15:25:08
【问题描述】:

页面位于 https://googlechrome.github.io/samples/service-worker/basic/ 拥有开始使用现代离线网页所需的所有脚本。在我偶然发现它之前,我花了很多徒劳的时间研究这个主题。突然间,我一直在阅读的所有内容开始变得有意义。 HTML5 再次给我留下了深刻的印象,因为它是一个出色的开发系统。

它有一个小脚本 sn-p 需要在你的主页上运行,它有一个服务工作者的完整脚本,当你在线时会从你的服务器获取文件 - 或者当你从缓存中获取它们时你离线了。

我花了不到一个小时就让它工作起来。注:您可以在 localhost 上使用 http 对其进行测试。任何其他服务器都需要 https 连接。 Google 和 Firefox 调试器不显示 serviceworker 的来源。

从一开始就很明显,serviceworker 示例中展示的功能非常接近我的应用所需的功能,但我认为我发现了一个错误。

激活处理程序应该负责清理旧缓存。这是脚本 - 来自页面的逐字记录。

// Names of the two caches used in this version of the service worker.
// Change to v2, etc. when you update any of the local resources, which will
// in turn trigger the install event again.
const PRECACHE = 'precache-v1';
const RUNTIME = 'runtime';

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

简而言之,它不会删除旧缓存。我认为它在执行过滤器以确定不需要哪些缓存之前尝试删除缓存。

我是一位经验丰富的程序员,但这个 sn-p 让我害怕。对于生产应用程序来说,它非常简短,但如果您正在调试它,则很难阅读。如果作者以更详细的方式编写它会很好,以便更多的开发人员可以了解发生了什么。

它是如何工作的?

【问题讨论】:

    标签: service-worker offline-caching offline-mode offline-browsing service-worker-events


    【解决方案1】:

    const PRECACHE = 'precache-v1'; const RUNTIME = '运行时间';

    self.addEventListener("activate", function(event) {
        event.waitUntil(
            caches.keys().then(function(cacheNames) {
                return Promise.all(
                    cacheNames.map(function(cacheName) {
                        if (PRECACHE !== cacheName && RUNTIME != cacheName) {
                            return caches.delete(cacheName);
                        }
                    })
                );
            })
        );
    });
        })
      );
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多