{"id":359,"date":"2023-11-23T18:35:05","date_gmt":"2023-11-23T10:35:05","guid":{"rendered":"https:\/\/blog.quantoyo.com\/?p=359"},"modified":"2023-11-23T18:35:05","modified_gmt":"2023-11-23T10:35:05","slug":"service-worker","status":"publish","type":"post","link":"https:\/\/blog.quantoyo.com\/?p=359","title":{"rendered":"Service worker"},"content":{"rendered":"\n<p>\u53ef\u4ee5\u62ff\u4f86\u505acache \u7684\u53e6\u4e00\u500b\u65b9\u5f0f<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>\u5728\u958b\u555f\u7db2\u9801\u6642\uff0c\u9700\u8981\u5148\u78ba\u8a8d\u8a72\u700f\u89bd\u5668\u662f\u5426\u652f\u6301serviceWorker\uff0c\u5982\u679c\u652f\u6301\uff0c\u5c31\u53ef\u4ee5\u4f9d\u7167 js \u5167\u5bb9\u4f86\u4f7f\u7528serviceWorker\u3002 <\/p>\n\n\n\n<p>register \u6642\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0cserviceWorker \u53ea\u80fdcache \u81ea\u5df1\u76ee\u9304 \u6216\u8005 \u4e0b\u5c64\u76ee\u9304 \u7684\u5167\u5bb9\uff0cscope \u53ef\u4ee5\u5728\u6b64\u6642\u6307\u5b9a\u3002<\/p>\n\n\n\n<p>\u5728\u6b64\u7bc4\u4f8b\u5167\u7684swFinal.js \u6709\u5e36\u8457\u7248\u672c\u865f\uff0c\u9019\u6a23\u624d\u80fd\u5728\u66f4\u65b0\u6a94\u6848\u5f8c\u7acb\u523b\u53cd\u61c9<\/p>\n\n\n\n<p>test.html \u5167\u5bb9<\/p>\n\n\n\n<pre class=\"wp-block-code has-light-gray-background-color has-background has-small-font-size\"><code>&lt;!DOCTYPE html>\n&lt;html lang=\"en\">\n   &lt;head>\n      &lt;link rel=\"manifest\" href=\"manifest.json\" crossorigin=\"use-credentials\">\n      &lt;script type=\"text\/javascript\">\n         if ( \"serviceWorker\" in navigator ) {\n            \/\/1. \u8def\u5f91\uff1a\u9019\u500bjs\u8def\u5f91\u6703\u5f71\u97ff\u80fd\u5b58\u53d6\u7684\u7bc4\u570d(\u8a72\u76ee\u9304\uff06\u4e0b\u5c64\u76ee\u9304)\uff0c\u653e\u6839\u76ee\u9304\u70ba\u6574\u7ad9\n            \/\/2. scope\uff1a\u653e\u7f6ejs \u6a94\u6848\u7684\u8def\u5f91\u4e0b\u7684\u67d0\u500b\u8def\u5f91\u624d\u6703cache.\n            \/\/ \u9810\u8a2d : navigator.serviceWorker.register( \"swFinal.js\" )\n            \/\/ \u52a0\u4e0ascope: navigator.serviceWorker.register( \"swFinal.js\",{scope: '.\/'} ) \/\/\u76f8\u7576\u65bc\u6c92\u5beb\n            \/\/ \u52a0\u4e0ascope: navigator.serviceWorker.register( \"swFinal.js\",{scope: '\/aaa\/'} ) \/\/\u653e\u7f6ejs \u6a94\u6848\u7684\u76ee\u9304\u4e0b\u7684aaa\u8cc7\u6599\u593e\u4e0b\u6a94\u6848\n            navigator.serviceWorker.register( \"swFinal.js?version=1.02\" )     \/\/\u6539\u7248\u865f\u5c31\u53ef\u4ee5\u63dbsw\uff0c\u907f\u514d\u4f7f\u7528\u5230\u539f\u672csw \u88e1\u9762\u6a94\u6848\u9084\u662f\u820a\u7684\n             .then( function ( registration ) { \n               console.log( \"ServiceWorker registration successful with scope: \", registration.scope );\n               const sw = registration.installing || registration.waiting || registration.active;\n               sw.postMessage({ milliseconds: Date.now() });\n             } ).catch( function ( err ) { \n               console.error( \"ServiceWorker registration failed: \", err );\n             } );\n         \n         }\n      &lt;\/script>\n   &lt;\/head>\n   &lt;body>\n      My awesome PWA\n   &lt;\/body>\n&lt;\/html>\n<\/code><\/pre>\n\n\n\n<p>swFinal.js \u662f\u8981register \u4f7f\u7528\u7684\u6a94\u6848\uff0c\u5167\u5bb9\u5305\u542b\u4e86<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>activate\uff1a\u555f\u52d5\u6642\uff0c\u6703\u81ea\u52d5\u547c\u53eb\u7684event\uff0c\u9019\u908a\u6703\u5c07\u6240\u6709cached \u7684\u6587\u4ef6\u505a\u4e00\u6b21\u6aa2\u67e5\uff0c\u4e26\u5254\u9664\u820a\u7684\u6a94\u6848\uff08\u975e\u76ee\u524d\u7248\u672c\uff09<\/li>\n\n\n\n<li>install \uff1a\u5728activate \u4e4b\u5f8c\u6703\u81ea\u52d5\u547c\u53eb\u7684event\uff0c\u6211\u5011\u5728\u9019\u908aadd \u6240\u6709\u9700\u8981cached \u7684\u6a94\u6848\uff0c\u53e6\u5916\u4e5f\u6dfb\u52a0\u4e00\u500bOFFLINE\u6642\u4f7f\u7528\u7684\u6a94\u6848<\/li>\n\n\n\n<li>fetch\uff1a\u53d6\u6a94\u6848\u7528\uff0c\u5982\u679ccache\u5167\u6709\u8a72\u6a94\u6848\uff0c\u5247\u76f4\u63a5\u53d6\u51fa\u4f7f\u7528\uff0c\u6c92\u6709\u5728\u5217\u8868\u5167\u4e5f\u53ef\u4ee5\u8a2d\u5b9aDYNAMIC_CACHE_LIMIT \u4f86\u555f\u52d5\u52d5\u614bcache \u6a5f\u5236\u3002\u7576\u7db2\u9801\u4f3a\u670d\u5668\u58de\u6389\uff0c\u4e5f\u6703\u8fd4\u56de\u539f\u672ccached \u7684OFFLINE \u9801\u9762\u3002<\/li>\n<\/ol>\n\n\n\n<p>swFinal.js \u5167\u5bb9<\/p>\n\n\n\n<pre class=\"wp-block-code has-light-gray-background-color has-background has-small-font-size\"><code>const VERSION = \"1.02\";\nconst DYNAMIC_CACHE_LIMIT = 0;\nconst CACHE_DYNAMIC_NAME = \"dynamic-\" + VERSION;\nconst CACHE_STATIC_NAME = \"static-\" + VERSION;\nconst STATIC_FILES = &#91;\n        '\/',\n        '\/index.html?version=1.01',\n        '\/testCache2.html?version=1.01',\n        'https:\/\/fonts.googleapis.com\/css?family=Noto+Sans+TC&amp;display=swap',\n        'https:\/\/fonts.googleapis.com\/icon?family=Material+Icons',\n        'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/material-design-lite\/1.3.0\/material.indigo-pink.min.css'\n    ];\nconst OFFLINE_URL  = \"\/offline.html\";                                                 \/\/\u9019\u500b\u662f\u8b93\u6709\u8dd1\u904e\u6b64service worker \u9810\u8f09\u5f8c\uff0c\u7db2\u8def\u65b7\u4e86\u53c8\u8981\u8f09\u5165\u4e0d\u5728\u5217\u8868\u5167\u7684\u6a94\u6848\u6642\uff0c\u9810\u8a2d\u8f09\u5165\u6b64\u6a94\u6848\n\nself.addEventListener('message', function(event) {\n     console.log('&#91;Service Worker] Message Service Worker ...', event);\n});\n\nself.addEventListener('activate', function(event) {\n    console.log('&#91;Service Worker] Activating Service Worker ...', event);\n    event.waitUntil(\n        caches.keys().then(function(keyList) {\n            return Promise.all(keyList.map(function(key) {\n                if(key !== CACHE_STATIC_NAME &amp;&amp; key !== CACHE_DYNAMIC_NAME) {       \/\/\u904d\u5c0b\u6240\u6709cache \u522a\u9664\u975e\u76ee\u524d\u7248\u672c\u7684\n                    console.log('&#91;Service Worker] Removing old cache.', key);\n                    return caches.delete(key);\n                }\n            }));\n        })\n    );\n    return self.clients.claim();\n});\n\/*  Service Worker Event Handlers *\/\nself.addEventListener('install', function(event) {\n    console.log('&#91;Service Worker] Installing Service Worker ...', event);\n    event.waitUntil(\n        caches.open(CACHE_STATIC_NAME).then(function(cache) {\n            console.log('&#91;Service Worker] Precaching App Shell');\n            cache.addAll(STATIC_FILES);                                             \/\/\u9019\u908a\u9810\u8f09\u5217\u8868\u5167\u7684\u6240\u6709\u6a94\u6848\u5230cache.\n            cache.add(OFFLINE_URL);                                                 \/\/\u9019\u908a\u9810\u8f09\u5217\u8868\u5167\u7684\u6240\u6709\u6a94\u6848\u5230cache.\n        })\n    );\n    self.skipWaiting();                                                             \/\/\u5047\u8a2d\u539f\u672c\u6709\u53e6\u4e00\u500b\u5206\u9801\u958b\u555f\u540c\u4e00\u500bsw\uff0c\u6703\u76f4\u63a5\u84cb\u6389\uff0c\u800c\u4e0d\u662f\u9810\u8a2d\u7684waiting.\n});\n\nself.addEventListener('fetch', function(event) {\n    \/\/ Cache with Network Fallback\n    event.respondWith(\n        caches.match(event.request).then(function(response) {\n            if(response) {                                                          \/\/\u5728cache \u5167\u627e\u5230\n                return response;                                                    \/\/\u56de\u50b3cache \u5167\u5bb9\n            } else {                                                                \/\/cache \u5167\u6c92\u6709\uff0c\u7528fetch\u53bb\u6293\u4e26\u5b58\u8d77\u4f86\n                return fetch(event.request).then(function(res) {\n                    return caches.open(CACHE_DYNAMIC_NAME).then(function(cache) {   \/\/\u52d5\u614b\u7684\uff0c\u5b58\u5230\u52d5\u614b\u7684cache \u5206\u985e\u4e2d\n                        if(DYNAMIC_CACHE_LIMIT > 0){\n                            trimCache(CACHE_DYNAMIC_NAME, DYNAMIC_CACHE_LIMIT);         \/\/\u52d5\u614bcache \u7684\u90e8\u5206\uff0c\u52a0\u4e0a\u6578\u91cf\u9650\u5236\n                            cache.put(event.request.url, res.clone());                  \/\/\u52a0\u5165\u52d5\u614bcache\n                        }\n                        return res;\n                    })\n                }).catch(function(err) {\n                    return caches.open(CACHE_STATIC_NAME).then(function(cache) {    \/\/fetch\u5931\u6557(\u6c92\u7db2\u8def)\n                        if(event.request.headers.get('accept').includes('text\/html')) {\n                            return cache.match(OFFLINE_URL);                        \/\/\u8fd4\u56de\u9810\u8a2d\u7684\u65b7\u7dda\u756b\u9762\n                        }\n                    });\n                });\n            }\n        })\n    );\n});\n\nfunction trimCache(cacheName, maxItems) {\n    caches.open(cacheName).then(function(cache) {\n        return cache.keys().then(function(keys) {\n            if(keys.length > maxItems) {\n                cache.delete(keys&#91;0]).then(trimCache(cacheName, maxItems));\n            }\n        });\n    })\n}<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p>\u53c3\u8003\u8cc7\u6599\uff1a<\/p>\n\n\n\n<p><a href=\"https:\/\/ithelp.ithome.com.tw\/articles\/10220322\">https:\/\/ithelp.ithome.com.tw\/articles\/10220322<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u53ef\u4ee5\u62ff\u4f86\u505acache \u7684\u53e6\u4e00\u500b\u65b9\u5f0f<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[46,56],"class_list":["post-359","post","type-post","status-publish","format-standard","hentry","category-technology","tag-javascript","tag-serviceworker"],"_links":{"self":[{"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=\/wp\/v2\/posts\/359","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=359"}],"version-history":[{"count":1,"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=\/wp\/v2\/posts\/359\/revisions"}],"predecessor-version":[{"id":360,"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=\/wp\/v2\/posts\/359\/revisions\/360"}],"wp:attachment":[{"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=359"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=359"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.quantoyo.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=359"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}