关于Service Worker

ServiceWorker是一种新的Web标准接口(可能也没有那么新了),属于一种worker thread
可以完成后台同步、消息推送、离线应用等工作。主要参考了google上的这篇文章

这个图片介绍了ServiceWorker的生命周期。

ServiceWorker生命周期

ServiceWorker是浏览器后台开的处理线程,通过register注册后执行。

它有一些标准的事件定义

  • 初始化会触发install事件
  • 当浏览器请求后台参数时,会触发fetch事件。
  • 当WorkerThread正式开始运行时,触发activate事件
//注册WorkerThread,这是在页面中的
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}
//install事件处理,在sw.js中
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
  '/',
  '/styles/main.css',
  '/script/main.js'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

这里通过fetch事件处理,可以缓存之前的请求,这样当页面发出请求时,可以通过该线程返回之前返回的数据,达到离线运行的目的。

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }

        return fetch(event.request).then(
          function(response) {
            // Check if we received a valid response
            if(!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT: Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            var responseToCache = response.clone();

            caches.open(CACHE_NAME)
              .then(function(cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      })
    );
});
posted @ 2020-03-31 22:46  mosakashaka  阅读(116)  评论(0编辑  收藏  举报