uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

PWA/Service Worker #226

Open uniquejava opened 6 years ago

uniquejava commented 6 years ago

Service Worker界于Page(Browser)和Web Server之间, 能拦截所有的request/response.

A Service Worker is run in a worker context, which means it has no DOM access and runs on a different thread from the main JavaScript that powers your app, so it’s not blocking. Service Workers are designed to be fully async, and as a consequence, you can’t access things such as synchronous XHR and localStorage. The Service Worker sits on a different thread and is able to intercept network requests. Service Workers are like air traffic controllers in that they give you total control of network requests coming and going from your website. This ability makes them extremely powerful and allows you to decide how to respond.

pwa

来源: Manning Progressive Web Apps

开启Serive Worker(写在index.html中):

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
  .then(function(registration) {
    console.log('Registration successful, scope is:', registration.scope);
  })
  .catch(function(error) {
    console.log('Service worker registration failed, error:', error);
  });
}

实现service-worker.js

uniquejava commented 6 years ago

Notes

  1. Service Worker中的cache永不过期(即使version变化, 旧版cache依然存在), 需要在activate事件中清除缓存
  2. cache.add相当于先fetch再put. , 而cache.addAll会递归调用add, 并且只要有一个cache的url失败, 则全部失败.(所以一定要注意cache的东西真实存在) 2.cache.put(key, response)这个key即可以是Request对象, 也可以是url字符串.
  3. 如果是request对象, 那么需要clone一份先cache.put(request.clone(), response)
  4. event.waitUntil会延长install的生命线, 直到promise解析成功, install才算完成.

全局对象caches https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage

delete() has() keys() match() 会递归调用cache的match方法 open()

cache的方法 https://developer.mozilla.org/en-US/docs/Web/API/Cache

add() addAll() delete() keys() match() matchAll() put()

为什么要clone require/response What happens when you read a response?

实例: https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/selective-caching/service-worker.js