[PWA] 2. Service worker life cycle

本文解析了Service Worker的工作机制,包括初次加载时为何无法看到日志,以及更新Service Worker后为何不会立即生效的原因。文章进一步解释了Service Worker版本更替的触发条件。
  1. Once serive worker is registered, the first time we go to the app, we cannot see the logs from servcie works. Any only refersh it second time, then we able to see the logs.
  2. Once we change service worker, it doesn't seem that we have change it.

 

The No1. is because, service worker only take control after it is loaded. But the first time we go to the page, service worker actually is not there, because, the browser need to fetch our assets, css, and Javascript fiels which include our sw.js. So that's why the first time we go to page, we didn't see the logs. But after we refresh the page, the sw.js is already cached. So the service worker can control from now on.

 

The No2. is because, once we change the code, it will check with service worker and if it is changed, it will become next version of serive worker. BUT it doesn't take control, it WATIS. It won't take control unitl all page use current version are gone. And a refresh doens't help, it because a overlap bewteen window client. Only you close the current page or naviagte to a page that isn't controlled by current service worker. When it does that, the new version of servie worker will take control.

 

So if you change the code a little bit:

self.addEventListener('fetch', function(event) {
  console.log("yo ",event.request);
});

 

And then close the current page, then open it again, you will see the new logs come out:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值