gpt4 book ai didi

javascript - 服务 worker : Fetch event listener only works after page reload

转载 作者:数据小太阳 更新时间:2023-10-29 05:49:20 26 4
gpt4 key购买 nike

我已经使用以下代码在我的页面中添加了一个服务 worker 。一旦页面被重新加载并且 worker 已经安装,它就可以很好地工作。但是在我看到'SW INSTALL' 日志后,在重新加载页面之前似乎没有捕捉到任何获取事件。

app.js

navigator.serviceWorker.register('/worker.js').then((registration) =>
{
console.log('ServiceWorker registration successful with scope: ',
registration.scope);
}, (err) =>
{
console.log('ServiceWorker registration failed: ', err);
});

worker.js

self.addEventListener('install', function (event)
{
console.log("SW INSTALL");
});

self.addEventListener('fetch', function (event)
{
console.log("FETCHING", event);
event.respondWith(
caches.match(event.request)
.then(function (response, err)
{
// Cache hit - return response
if (response)
{
console.log("FOUND", response, err);
return response;
}
console.log("MISSED", event.request.mode);
return fetch(event.request)
}
)
);
});

最佳答案

解决方案:将以下内容添加到 worker.js;

self.addEventListener('activate', function (event)
{
event.waitUntil(self.clients.claim());
});

Service workers don’t immediately “claim” the sessions that load them, meaning that until your user refreshes the page your service worker will be inactive.

The reason for this is consistency, given that you might otherwise end up with half of your webpage’s assets cached and half uncached if a service worker were to come alive partway through your webpage’s initialization. If you don’t need this safeguard, you can call clients.claim and force your service worker to begin receiving events

阅读更多@ service-workers

关于javascript - 服务 worker : Fetch event listener only works after page reload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45007878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com