TL; DR - 我希望我的服务工作者在第一次访问我的网站后立即激活,而不是在第一次刷新之后激活。
细节:
我已经使用服务工作者构建了一个渐进式Web应用程序,但是注意到在第一次加载时(安装SW时),在用户刷新页面之前,它不会拦截任何网络请求。
有什么办法可以让服务工作者在安装后立即开始拦截请求吗?
TL; DR - 我希望我的服务工作者在第一次访问我的网站后立即激活,而不是在第一次刷新之后激活。
细节:
我已经使用服务工作者构建了一个渐进式Web应用程序,但是注意到在第一次加载时(安装SW时),在用户刷新页面之前,它不会拦截任何网络请求。
有什么办法可以让服务工作者在安装后立即开始拦截请求吗?
你的确可以通过组合使用 skipWaiting
和 clients.claim
如下所示。
这将使服务工作者立即控制来自页面的网络请求。
self.addEventListener('install', event => {
// Bypass the waiting lifecycle stage,
// just in case there's an older version of this SW registration.
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', event => {
// Take control of all pages under this SW's scope immediately,
// instead of waiting for reload/navigation.
event.waitUntil(self.clients.claim());
});
你的确可以通过组合使用 skipWaiting
和 clients.claim
如下所示。
这将使服务工作者立即控制来自页面的网络请求。
self.addEventListener('install', event => {
// Bypass the waiting lifecycle stage,
// just in case there's an older version of this SW registration.
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', event => {
// Take control of all pages under this SW's scope immediately,
// instead of waiting for reload/navigation.
event.waitUntil(self.clients.claim());
});