页面位于https://googlechrome.github.io/samples/service-worker/basic/提供了现代脱机网页入门所需的所有脚本。在迷迷糊糊之前,我花了许多无用的时间来研究该主题。突然之间,我一直在阅读的所有东西开始变得有意义。 HTML5再一次给我留下了深刻的印象,它是一个出色的开发系统。
它有一小段脚本,需要在您的主页上运行,它具有服务人员的完整脚本,可以在您在线时从服务器中获取文件,或者在您处于在线状态时从缓存中获取文件离线。
我花了不到一个小时的时间才能开始工作。 N.B.您可以使用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())
);
});
简单地说,它不是删除旧的缓存。我认为它正在尝试在执行过滤器以确定不需要的缓存之前删除缓存。
我是一位经验丰富的程序员,但是这段代码使我感到恐惧。对于生产应用程序来说,它很漂亮,但如果您对其进行调试,则很难阅读。如果作者以更冗长的方式编写它,这样会更好,以便更多的开发人员可以了解正在发生的事情。
如何运作?
const PRECACHE ='precache-v1';const RUNTIME ='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);
}
})
);
})
);
});
})
);
});