服务工作者:Fetch事件侦听器仅在页面重新加载后才起作用 [英] Service worker: Fetch event listener only works after page reload

查看:112
本文介绍了服务工作者:Fetch事件侦听器仅在页面重新加载后才起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的页面中添加了一个服务工作者,其代码如下。一旦重新加载页面并且已经安装了工作程序,它就能很好地工作。但在我看到'SW INSTALL'日志之后,在重新加载页面之前似乎没有抓到任何获取事件。

I have added a service worker to my page with the code below. It works well once the page has been reloaded and the worker already installed. But does not seem to catch any fetch events before the page is reloaded after I have seen the 'SW INSTALL' log.

app.js

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

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;

Solution: Adding the following to 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.

这样做的原因是一致性,因为您可能会如果一个
的服务工作者在你的网页的
初始化中途活跃起来,那么结束你的网页资产的一半被缓存,一半结束
。如果您不需要此保护措施,可以拨打
clients.claim并强制您的服务人员开始接收活动

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

阅读更多内容@ 服务工作者

这篇关于服务工作者:Fetch事件侦听器仅在页面重新加载后才起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆