ExtendableEvent
注意:此功能仅在 Service Workers 中可用。
ExtendableEvent 接口扩展了在服务工作线程生命周期中分派到全局作用域的 install 和 activate 事件的生命周期。这确保了任何功能性事件(如 FetchEvent)在升级数据库模式和删除过时缓存条目之前不会被分派。
如果在 ExtendableEvent 处理程序之外调用 waitUntil(),浏览器应抛出 InvalidStateError;另请注意,多次调用将堆叠起来,并且生成的 Promise 将被添加到 extend lifetime promises 列表中。
此接口继承自 Event 接口。
注意:此接口仅在全局作用域为 ServiceWorkerGlobalScope 时可用。当它是 Window 或其他类型的 worker 的作用域时,它不可用。
构造函数
ExtendableEvent()-
创建一个新的
ExtendableEvent对象。
实例属性
没有实现任何特定的属性,但继承了其父级 Event 的属性。
实例方法
继承自其父级 Event 的方法.
ExtendableEvent.waitUntil()-
扩展事件的生命周期。它旨在被调用在
installingworker 的install事件处理程序中,以及在activeworker 的activate事件处理程序上。
示例
此代码片段来自 service worker prefetch sample(请参阅 prefetch 示例在线)。该代码在 oninstall 中调用 ExtendableEvent.waitUntil(),推迟将 ServiceWorkerRegistration.installing worker 视为已安装,直到传入的 Promise 成功解析。当所有资源都已获取并缓存,或者发生任何异常时,Promise 就会解析。
该代码片段还展示了服务工作线程使用的缓存版本控制的最佳实践。尽管此示例中只有一个缓存,但相同的方法可用于多个缓存。它将缓存的简写标识符映射到特定的、已版本的缓存名称。
注意:在 Chrome 中,可以通过 "Inspect" 界面查看与相关服务工作线程相关的日志记录语句,该界面可通过 chrome://serviceworker-internals 访问。
const CACHE_VERSION = 1;
const CURRENT_CACHES = {
prefetch: `prefetch-cache-v${CACHE_VERSION}`,
};
self.addEventListener("install", (event) => {
const urlsToPrefetch = [
"./static/pre_fetched.txt",
"./static/pre_fetched.html",
"https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif",
];
console.log(
"Handling install event. Resources to pre-fetch:",
urlsToPrefetch,
);
event.waitUntil(
caches
.open(CURRENT_CACHES["prefetch"])
.then((cache) =>
cache.addAll(
urlsToPrefetch.map(
(urlToPrefetch) => new Request(urlToPrefetch, { mode: "no-cors" }),
),
),
)
.then(() => {
console.log("All resources have been fetched and cached.");
})
.catch((error) => {
console.error("Pre-fetching failed:", error);
}),
);
});
注意:在获取资源时,如果资源可能由不支持 CORS 的服务器提供,则使用 {mode: 'no-cors'} 非常重要。在此示例中,www.chromium.org 不支持 CORS。
规范
| 规范 |
|---|
| Service Workers # extendableevent-interface |
浏览器兼容性
加载中…