[关闭]
@duanyubin 2018-06-15T02:35:03.000000Z 字数 2911 阅读 465

Offline Cache

javascript


https://www.youtube.com/watch?v=jCKZDTtUA2A
https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

Service Worker

Proxy between browser and network

BEFORE:
service-worker

AFTER:
service-worker

Features

Life Cycle

  1. 通过register来获取和注册,注意scope
  2. install
    1. installing
    2. installed 已经安装完毕,等待使用旧的service worker的client被关闭
    3. activating 没有使用旧的sw的client,此时可以清除旧的cache
  3. activated handle function(fetch、sync、push),可以代理请求,
  4. redundant 被别的sw替代,失效

1. Register A service worker

  1. if ('serviceWorker' in navigator) {
  2. window.addEventListener('load', function() {
  3. navigator.serviceWorker.register('/path/sw.js', { scope: '/path/' }).then(function(registration) {
  4. // Registration was successful
  5. console.log('ServiceWorker registration successful with scope: ', registration.scope);
  6. }, function(err) {
  7. // registration failed :(
  8. console.log('ServiceWorker registration failed: ', err);
  9. });
  10. });
  11. }

disable sw.js http cache

If we register service worker at /path/sw.js, only pages like /path/page1 /path/page2 will be under control by service worker.

2. Install a service worker

Decide which files you want to cache

  1. self.addEventListener('install', function(event) {
  2. // 1. Open a cache.
  3. // 2. Cache our files.
  4. // 3. Confirm whether all the required assets are cached or not.
  5. event.waitUntil(
  6. caches.open('v1').then(function(cache) {
  7. return cache.addAll([
  8. '/sw-test/',
  9. '/sw-test/index.html',
  10. '/sw-test/style.css',
  11. '/sw-test/app.js',
  12. '/sw-test/image-list.js',
  13. '/sw-test/star-wars-logo.jpg',
  14. '/sw-test/gallery/',
  15. '/sw-test/gallery/bountyHunters.jpg',
  16. '/sw-test/gallery/myLittleVader.jpg',
  17. '/sw-test/gallery/snowTroopers.jpg'
  18. ]);
  19. })
  20. );
  21. });

3. Cache and return requests

Recieve request and return response cache if exist

  1. this.addEventListener('fetch', function(event) {
  2. event.respondWith(
  3. caches.match(event.request).catch(function() {
  4. return fetch(event.request);
  5. })
  6. );
  7. });

4. Update a service worker

  1. this.addEventListener('activate', function(event) {
  2. var cacheWhitelist = ['v2'];
  3. event.waitUntil(
  4. caches.keys().then(function(keyList) {
  5. return Promise.all(keyList.map(function(key) {
  6. if (cacheWhitelist.indexOf(key) === -1) {
  7. return caches.delete(key);
  8. }
  9. }));
  10. })
  11. );
  12. });

workbox

sw-precache vs sw-toolbox

precache vs toolbox

precache

  1. staticFileGlobs: [
  2. './dist/js/**/*.js',
  3. './dist/css/*.css',
  4. './dist/img/**/*',
  5. './dist/*.html'
  6. ],
  7. stripPrefixMulti: {
  8. './dist/js/': `${cdnPrefix}/js/`,
  9. './dist/css/': `${cdnPrefix}/css/`,
  10. './dist/img/': `${cdnPrefix}/img/`,
  11. './dist/': dev ? '/' : `https://xxx/${projectName}/`
  12. }

After compilation:

  1. self.__precacheManifest = [
  2. {
  3. "url": "http://localhost:3000/css/detail.79e341dd393ad094529c.css",
  4. "revision": "a2eef255ee6f166e4050a6226270beb4"
  5. },
  6. {
  7. "url": "http://localhost:3000/js/detail.ede7025524a699a749bb.js",
  8. "revision": "e532f0c17656a3e1a9081fd1dcd11aac"
  9. }
  10. ]

runtimeCaching

  1. runtimeCaching: [{
  2. urlPattern: /https:\/\/s3.pstatp.com\/pgc\/tech\/collect\/collect-.*/,
  3. handler: 'cacheFirst',
  4. options: {
  5. cacheName: 'tea-sdk'
  6. }
  7. }, {
  8. urlPattern: /https:\/\/m.dcdapp.com\/motor\/brand\/m\/v1\/brand/,
  9. handler: 'staleWhileRevalidate',
  10. options: {
  11. cacheName: 'brand-list'
  12. }
  13. }],

Handlers

staleWhileRevalidate

precache vs toolbox

networkFirst

precache vs toolbox

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注