MDN 建议您执行以下操作来创建和填充服务工作线程缓存:
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/sw-test/',
'/sw-test/index.html',
... etc ...
]);
})
);
});
我不明白该代码。 waitUntil
方法也有文档记录,上面的代码似乎是它目前存在的唯一目的:
The ExtendableEvent.waitUntil() method extends the lifetime of the event. When called in an EventHandler associated to the install event, it delays treating the installing worker as installed until the passed Promise resolves successfully. This is primarily used to ensure that a service worker is not considered installed until all of the core caches it depends on are populated.
我不明白的是:
waitUntil
通常如何影响代码流?它会阻止事件传播直到它的 promise 得到解决吗?- 为什么在打开工作缓存的情况下需要它?
我问这个问题是因为我对上面的代码有疑问,我想理解它。
最佳答案
正如描述所说:
the
ExtendableEvent.waitUntil()
method extends the lifetime of the event.
如果您不在方法内调用它,则服务工作线程可能随时停止(请参阅 the specification )。
因此,waitUntil
方法用于告诉浏览器不要终止 Service Worker,直到传递给 waitUntil
的 Promise 得到解决或拒绝。
关于您的具体问题:
- 对于
install
和activate
事件,它会延迟 Service Worker 到installed
和的状态切换已激活
(请参阅 specification of the waitUntil method ,特别是该段落的最后一部分)。 - 我认为我的答案的其余部分已经回答了为什么需要它。
关于javascript - event.waitUntil 在 Service Worker 中做什么以及为什么需要它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902441/