serviceworker注册配置

注册serviceworker

首先创建一个公共脚本文件(registerSW.js)

/*
使用方法:
1. 将serviceworker.js放置在网站发布的根目录
2. serviceworker.js文件引入完成之后,再在全局配置文件里面写入下面内容,
    或者直接引入当前文件
*/
/*
在页面中        
        <script src="/js/registerSW.js?v=xxx"></script>
*/
// 延迟注册serviceWorker
window.addEventListener('load', function() {
  if('serviceWorker' in navigator){
     // serviceworker.js 文件要放在网站发布的根目录
     navigator.serviceWorker.register('/serviceworker.js').then(function (registration) {
      console.log('Service Worker Registered,register script: serviceworker.js.');
    }).catch(function (error) {
      // registration failed
      console.log('Registration failed with ' + error);
    });
  }
});
// 控制台显示service worker缓存占用情况
if ('storage' in navigator && 'estimate' in navigator.storage) {
    navigator.storage.estimate().then(estimate => {
        console.log(`Using ${estimate.usage/1024/1024} out of ${estimate.quota/1024/1024} MB.And the proportion is ${estimate.usage/estimate.quota*100}%`);
    });
}

然后,将以上文件引入公共部分

<script src="https://www.domain.com/js/registerSW.js"></script>

当然,将以上脚本内容直接复制到已有的公共文件也可以。

配置serviceworker

然后在网站的发布根目录创建文件(serviceworker.js)

'use strict';
/*  
本文件要放在网站发布的根目录
*/
const version = 'v20180608'; //这里是填写版本号可自定义,一旦这个文件修改了,请务必修改版本号
const __DEVELOPMENT__ = false;
const __DEBUG__ = false;
const offlineResources = [   //离线断网的时候提供友好界面
  '/',
  '/offline.html',
  '/offline.svg'
];
const ignoreFetch = [           //这里是需要忽略的第三方的域名
  /chrome-extension:\/\//,     // 建议加上忽略chrome插件的协议
  /https?://cdn.bootcss.com//,
  /https?://zz.bdstatic.com//,
  /https?://s.360.cn//,
  /https?://s.ssl.qhres.com//,
  /https?://hm.baidu.com//,
  /https?://s19.cnzz.com//,
  /https?://sp0.baidu.com//,
  /https?://tag.baidu.com//,
  /https?://msite.baidu.com//,
  /https?://s.bdstatic.com//,
  /https?://timg01.bdimg.com//,  
];
//////////
// Install
//////////
function onInstall(event) {
  log('install event in progress.');
  event.waitUntil(updateStaticCache());
}
function updateStaticCache() {
  return caches
    .open(cacheKey('offline'))
    .then((cache) => {
      return cache.addAll(offlineResources);
    })
    .then(() => {
      log('installation complete!');
    });
}
////////
// Fetch
////////
function onFetch(event) {
  const request = event.request;
  if (shouldAlwaysFetch(request)) {
    event.respondWith(networkedOrOffline(request));
    return;
  }
  if (shouldFetchAndCache(request)) {
    event.respondWith(networkedOrCached(request));
    return;
  }
  event.respondWith(cachedOrNetworked(request));
}
function networkedOrCached(request) {
  return networkedAndCache(request)
    .catch(() => { return cachedOrOffline(request) });
}
// Stash response in cache as side-effect of network request
function networkedAndCache(request) {
  return fetch(request)
    .then((response) => {
      var copy = response.clone();
      caches.open(cacheKey('resources'))
        .then((cache) => {
          cache.put(request, copy);
        });
      log("(network: cache write)", request.method, request.url);
      return response;
    });
}
function cachedOrNetworked(request) {
  return caches.match(request)
    .then((response) => {
      log(response ? '(cached)' : '(network: cache miss)', request.method, request.url);
      return response ||
        networkedAndCache(request)
          .catch(() => { return offlineResponse(request) });
    });
}
function networkedOrOffline(request) {
  return fetch(request)
    .then((response) => {
      log('(network)', request.method, request.url);
      return response;
    })
    .catch(() => {
      return offlineResponse(request);
    });
}
function cachedOrOffline(request) {
  return caches
    .match(request)
    .then((response) => {
      return response || offlineResponse(request);
    });
}
function offlineResponse(request) {
  log('(offline)', request.method, request.url);
  if (request.url.match(/\.(jpg|png|gif|svg|jpeg)(\?.*)?$/)) {
    return caches.match('/offline.svg');
  } else {
    return caches.match('/offline.html');
  }
}
///////////
// Activate
///////////
function onActivate(event) {
  log('activate event in progress.');
  event.waitUntil(removeOldCache());
}
function removeOldCache() {
  return caches
    .keys()
    .then((keys) => {
      return Promise.all( // We return a promise that settles when all outdated caches are deleted.
        keys
         .filter((key) => {
           return !key.startsWith(version); // Filter by keys that don't start with the latest version prefix.
         })
         .map((key) => {
           return caches.delete(key); // Return a promise that's fulfilled when each outdated cache is deleted.
         })
      );
    })
    .then(() => {
      log('removeOldCache completed.');
    });
}
function cacheKey() {
  return [version, ...arguments].join(':');
}
function log() {
  if (developmentMode()) {
    console.log("SW:", ...arguments);
  }
}
function shouldAlwaysFetch(request) {
  return __DEVELOPMENT__ ||
    request.method !== 'GET' ||
      ignoreFetch.some(regex => request.url.match(regex));
}
function shouldFetchAndCache(request) {
  return ~request.headers.get('Accept').indexOf('text/html');
}
function developmentMode() {
  return __DEVELOPMENT__ || __DEBUG__;
}
log("Hello from ServiceWorker land!", version);
self.addEventListener('install', onInstall);
self.addEventListener('fetch', onFetch);
self.addEventListener("activate", onActivate);

经过以上步骤,当打开页面的时候在控制台就可以看到相关信息

results matching ""

    No results matching ""