Skip to content

Commit ce6bcf4

Browse files
committed
update active listener for sw
1 parent 2e554cf commit ce6bcf4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

_blogs/HTML5/ServiceWorker/ServiceWorker最佳实践.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,43 @@ event.respondWith(
140140
);
141141
```
142142

143+
### 外部 service worker 激活时的回调
144+
145+
在确认 service worker 已经激活后,再进行请求,避免 service worker 还未激活就发出请求,导致请求失败。
146+
147+
```js
148+
export const waitUntil = (
149+
checker: () => boolean,
150+
option?: { timeout?: number, max?: number }
151+
) =>
152+
new Promise((resolve, reject) => {
153+
const { timeout = 100, max = 0 } = option ?? {};
154+
let start = Date.now();
155+
const id = setInterval(() => {
156+
if (checker()) {
157+
clearInterval(id);
158+
resolve(true);
159+
} else if (max > 0 && Date.now() - start > max) {
160+
clearInterval(id);
161+
reject("waitUntil max time run out.");
162+
}
163+
}, timeout);
164+
});
165+
166+
// check if service worker is active
167+
waitUntil(() => !!navigator.serviceWorker.controller, { max: 10000 }).then(
168+
() => {
169+
fetch(`/hi`);
170+
}
171+
);
172+
```
173+
174+
[ServiceWorkerContainer.controller](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller)
175+
176+
> The controller read-only property of the ServiceWorkerContainer interface returns a ServiceWorker object if its state is activating or activated (the same object returned by ServiceWorkerRegistration.active). This property returns null if the request is a force refresh (Shift + refresh) or if there is no active worker.
177+
178+
此属性 只有在 当前页面 有 active service worker 时才会返回 service worker 实例,否则返回 null
179+
143180
## 一些技巧
144181
145182
### 如何在 Next.ts 中引入 service worker

0 commit comments

Comments
 (0)