SW - Service Worker
下面来简单解析下hello world
register
// TODO add service worker code here |
在程序入口注册serverWorker,当然要判断浏览器是否支持
注意Service worker程序所在目录就是他的作用域,一般放根目录下
install
var cacheName = 'weatherPWA-step-6-1'; |
安装的时候开启caches,把自己的cache列表加入caches
activate
self.addEventListener('activate', function (e) { |
激活的时候根据cacheName dataCacheName 来把不在列表中的东西从 cache干掉
dataCacheName存放请求的数据的
When the app is complete, self.clients.claim() fixes a corner case in which the app wasn’t returning the latest data. You can reproduce the corner case by commenting out the line below and then doing the following steps: 1) load app for first time so that the initial New York City data is shown 2) press the refresh button on the app 3) go offline 4) reload the app. You expect to see the newer NYC data, but you actually see the initial data. This happens because the service worker is not yet activated. self.clients.claim() essentially lets you activate the service worker faster.
fetch拦截
self.addEventListener('fetch', function(e) { |
不仅仅cache一些静态的资源,还可以拦截请求,并操作是否预先冲cache中取缓存数据
一般有两种策略
- 缓存有限
- 网络请求优先
app中应用
var url = 'https://query.yahooapis.com/v1/public/yql?format=json&q=' + statement; |
程序内应用 要先判断是否浏览器支持caches
如果请求的url可以匹配到,就先用cache更新UI
后面会请求更新最新数据,更新的时候需要判断网络请求回来的数据和cache里的那个是最新的(SW拿东西不一定就比网络快)
如果要在生产环境应用这个,还需调研 https://github.com/GoogleChrome/sw-precache