serviceWorker 服务器与浏览器之间的代理
生活随笔
收集整理的這篇文章主要介紹了
serviceWorker 服务器与浏览器之间的代理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
特點:.本質上充當服務器與瀏覽器之間的代理服務器(可以攔截全站的請求,并作出相應的動作->由開發者指定的動作).在web worker的基礎上增加了離線緩存的能力.由事件驅動的,具有生命周期,其生命周期與頁面無關(關聯頁面未關閉時,它也可以退出,沒有關聯頁面,它也可以啟動).可以訪問cache和indexDB.完全異步,同步API(如XHR和localStorage)不能在service work中使用.只能為https承載.服務于多個頁面的。(按照同源策略).不能緩存POST請求應用場景:.跟 Fetch 搭配,可以從瀏覽器層面攔截請求,做數據 mock;.跟 Fetch 和 CacheStorage 搭配,可以做離線應用;.跟 Push 和 Notification 搭配,可以做像 Native APP 那樣的消息推送激活流程:.在navigator.serviceWorker.register進行注冊后.用戶首次訪問service worker控制的網站或頁面時,service worker會立刻被下載.無論它與現有service worker不同(字節對比),還是第一次在頁面或網站遇到service worker,如果下載的文件是新的,安裝就會嘗試進行.安裝成功后它會被激活.如果現有service worker已啟用,新版本會在后臺安裝,但不會被激活,這個時序稱為worker in waiting.直到所有已加載的頁面不再使用舊的service worker才會激活新的service worker。只要頁面不再依賴舊的service worker,新的service worker會被激活(成為active worker)。跳過等待:this.skipWaiting(); 跳過installing,直接接管老的service worker,觸發activate,在self.addEventListener('install')中調用手動更新客戶端:self.clients.claim(),在self.addEventListener('activate')中清除完舊緩存后調用.之后,在以下情況將會觸發更新:.一個前往作用域內頁面的導航.在 service worker 上的一個事件被觸發并且過去 24 小時沒有被下載基本使用:Service Worker 注冊的代碼是放在 HTML 的最后,如果頁面加載時沒有Service Worker,那么它所依賴的其他資源請求也不會觸發 fetch 事件。1、注冊service worker.如果注冊成功,service worker就會被下載到客戶端并嘗試安裝或激活,這將作用于整個域內用戶可訪問的URL,或者其特定子集navigator.serviceWorker.register(url,options)url:service worker文件的路徑,路徑是相對于 Origin ,而不是當前文件的目錄的optiontsscope:表示定義service worker注冊范圍的URL ;service worker可以控制的URL范圍。通常是相對URL。默認值是基于當前的location(./),并以此來解析傳入的路徑.假設你的sw文件放在根目錄下位于/sw/sw.js路徑的話,那么你的sw就只能監聽/sw/*下面的請求,如果想要監聽所有請求有兩個辦法,一個是將sw.js放在根目錄下,或者是在注冊是時候設置scope。如設置為/app/即app地址路徑下的所有頁面如/app/index.html;/app/main/index.html。`避免第一次打開頁面就進行緩存,占用主線程的帶寬,以及加劇對cpu和內存的使用if ('serviceWorker' in navigator) {window.addEventListener('load', function() {navigator.serviceWorker.register('/sw.js');});}if ('serviceWorker' in window.navigator) {navigator.serviceWorker.register('./sw.js', { scope: './' }).then(function (res) {res:ServiceWorkerRegistration實例}).catch(function (err) {console.log('fail', err);});注冊多個service worker,但scope必須是不同的navigator.serviceWorker.register('./sw/sw.js', { scope: './sw' }).then(function (reg) {console.log('success', reg);})navigator.serviceWorker.register('./sw2/sw2.js', { scope: './sw2' }).then(function (reg) {console.log('success', reg);})}1.5、方法主線程中:(1)發送信息if ('serviceWorker' in window.navigator) {navigator.serviceWorker.register('./sw.js', { scope: './' }).then(function (reg) {方式一:.如果使用的scope不是Origin下使用.reg.active就是被注冊后激活 Serivce Worker 實例.由于Service Worker的激活是異步的,因此第一次注冊 Service Worker 的時候,Service Worker 不會被立刻激活, reg.active 為 nullreg.active.postMessage("this message is from page, to sw");方式二:確定當前serviceWorker已經激活安裝完成navigator.serviceWorker.controller && navigator.serviceWorker.controller.postMessage("this message is from page");方式三:通過messageChannel});方式四:navigator.serviceWorker.register('service-worker.js');navigator.serviceWorker.ready.then( registration => {registration.active.postMessage("Hi service worker");});(2)銷毀service workerif ('serviceWorker' in navigator) {//獲取所有注冊的service workernavigator.serviceWorker.getRegistrations().then(function(registrations) {for(let registration of registrations) {//安裝在網頁的service worker不止一個,找到我們的那個并刪除if(registration && registration.scope === 'https://seed.futunn.com/'){registration.unregister(); //進行銷毀}}});}(3)更新service workervar version = '1.0.1'navigator.serviceWorker.register('/sw.js').then((reg) => {if(localStorage.getItem('sw_version') !== version) {reg.update().then(() => {localStorage.setItem('sw_version', version)})}})在service worker腳本文件中:(1)發送消息this.addEventListener('message', function (event) {必須使用event.source進行發送,在其他能獲取到的函數中也可以event.source.postMessage('this message is from sw.js, to page');});方式二:.通過窗口發送,即注冊了該serviceWoker的頁面的clients對象(即windows對象).client必須要接收到頁面發送到serviceWorker的消息后才能發送消息this.clients.matchAll().then(client => {client[0].postMessage('this message is from sw.js, to page');})方式三:通過messageChannel2、監聽在service worker腳本文件中(1)監聽被下載安裝this.addEventListener('install', function (event) {console.log('Service Worker install');});var CACHE_VERSION = 1;var CURRENT_CACHES = {prefetch: 'prefetch-cache-v' + CACHE_VERSION};self.addEventListener('install', function(event) {var urlsToPrefetch = ['./static/pre_fetched.txt','./static/pre_fetched.html','https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif'];event.waitUntil(caches.open(CURRENT_CACHES['prefetch']).then(function(cache) {cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {return new Request(urlToPrefetch, {mode: 'no-cors'});})).then(function() {console.log('All resources have been fetched and cached.');});}).catch(function(error) {console.error('Pre-fetching failed:', error);}));});(2)監聽被激活.觸發時可以清理舊緩存和舊的service worker關聯的東西this.addEventListener('activate', function (event) {console.log('Service Worker activate');});(3)監聽信息發送this.addEventListener('message', function (event) {console.log(event.data); });(4)監聽瀏覽器請求this.addEventListener('fetch', function (event) {...}主線程監聽(1)監聽消息發送navigator.serviceWorker.addEventListener('message', function (e) {console.log(e.data); });(2)監聽service worker是否改變navigator.serviceWorker.addEventListener('controllerchange', () => {window.location.reload();})3、記錄service worker的生命周期if ('serviceWorker' in navigator) {$('#isSupport').text('支持');// 開始注冊service workersnavigator.serviceWorker.register('./sw-demo-cache.js', {scope: './'}).then(function (registration) {$('#isSuccess').text('注冊成功');var serviceWorker;if (registration.installing) {serviceWorker = registration.installing;$('#state').text('installing');} else if (registration.waiting) {serviceWorker = registration.waiting;$('#state').text('waiting');} else if (registration.active) {serviceWorker = registration.active;$('#state').text('active');}if (serviceWorker) {$('#swState').text(serviceWorker.state);serviceWorker.addEventListener('statechange', function (e) {$('#swState').append(' 狀態變化為' + e.target.state);});}}).catch (function (error) {$('#isSuccess').text('注冊沒有成功');});} else {$('#isSupport').text('不支持');}</script>4、離線背景同步.可以先將網絡相關任務延遲到用戶有網絡的時候再執行.可以用于保證任何用戶在離線的時候所產生對于網絡有依賴的操作,最終可以在網絡再次可用的時候抵達它們的目標。.離線期間所有相同事件只會觸發一次,如果希望每一次點擊都能觸發 sync 事件,就需要在注冊的時候賦予它們不同的tag。navigator.serviceWorker.ready .then(registration => {document.getElementById('submit').addEventListener('click', () => {背景同步操作registration.sync.register('submit').then(() => {console.log('sync registered!');});});});service worker中: self.addEventListener('sync', event => { if (event.tag === 'submit') {console.log('sync!');}});5、最佳實踐為了保證離線緩存的資源和真實資源一致,優先使用在線資源(即http請求),sw充當本地和線上服務器的代理服務器角色;當在線資源獲取出錯(服務器宕機,網絡不可用等情況),則使用sw本地緩存優先從線上獲取,獲取之后設置緩存,以便下一次獲取html出錯時候再從本地緩存獲取的是上一次獲取的文件請求攔截:this.addEventListener('fetch', function (event) {if(event.request.method === 'POST') {event.respondWith(new Promise(resolve => {event.request.json().then(body => {console.log(body); // 用戶請求攜帶的內容})resolve(new Response({ a: 2 })); // 返回的響應}))}}}self.addEventListener('fetch', function(event) { event.respondWith(caches.match(event.request).then(function(response) {if (response) {return response;}return fetch(event.request).then(function(response) {return response;}).catch(function(error) {throw error;});}));});頁面緩存:通過Cache Stroage或indexDB進行存儲因為oninstall和onactivate完成前需要一些時間,service worker標準提供一個waitUntil方法,當oninstall或者onactivate觸發時被調用,接受一個promiseevent.waitUntil.只能在 Service Worker 的 install 或者 activate 事件中使用;.如果傳遞了一個 Promise 給它,那么只有當該 Promise resolved 時,Service Worker 才會完成 install;.如果 Promise rejected 掉,那么整個 Service Worker 便會被廢棄掉。因此,cache.addAll 里面,只要有一個資源獲取失敗,整個 Service Worker 便會失效。event.respondWith.只能在 Service Worker 的 fetch 事件中使用;.返回一個Promise,當傳入的 Promise resolved 之后,才會將對應的 response 返回給瀏覽器。.resolve的內容為 Response對象、a network error(1)靜態資源化緩存this.addEventListener('install', function (event) {event.waitUntil(caches.open('sw_demo').then(function (cache) {return cache.addAll(['/style.css','/panda.jpg','./main.js'])}));});(2)動態資源緩存this.addEventListener('fetch', function (event) {event.respondWith(caches.match(event.request).then(res => {return res ||fetch(event.request) 獲取真實資源并緩存.then(responese => {需要克隆一份,因為請求和響應流只能被讀取一次,為了給瀏覽器返回響應并且還要把它緩存起來,我們不得不克隆一份const responeseClone = responese.clone();caches.open('sw_demo').then(cache => {cache.put(event.request, responeseClone);})return responese;}).catch(err => {console.log(err);});}))});
代碼示例:
資源加載錯誤,導航錯誤頁
錯誤降級、清除worker
window.addEventListener('load', function() {const sw = window.navigator.serviceWorkerconst killSW = window.killSW || falseif (!sw) {return}if (!!killSW) {sw.getRegistration('/serviceWorker').then(registration => {// 手動注銷registration.unregister();// 清除緩存window.caches && caches.keys && caches.keys().then(function(keys) {keys.forEach(function(key) {caches.delete(key);});});})} else {// 表示該 sw 監聽的是根域名下的請求sw.register('/serviceWorker.js',{scope: '/'}).then(registration => {// 注冊成功后會進入回調console.log('Registered events at scope: ', registration.scope);}).catch(err => {console.error(err)})}});更新、清除緩存
// sw.js 更換緩存命名空間 this.addEventListener('install', function (event) {console.log('install');event.waitUntil(caches.open('sw_demo_v2').then(function (cache) { // 更換緩存命名空間return cache.addAll(['/style.css','/panda.jpg','./main.js'])})) });//新的命名空間 const cacheNames = ['sw_demo_v2'];// sw.js 校驗過期的緩存進行清除 this.addEventListener('activate', function (event) {event.waitUntil(caches.keys().then(keys => {return Promise.all[keys.map(key => {if (!cacheNames.includes(key)) {console.log(key);return caches.delete(key); // 刪除不在白名單中的其他命名空間的 Cache Stroage}})]})) });雨雀官網的緩存
self.assets = ["https://gw.alipayobjects.com/os/chair-script/skylark/common.b4c03be5.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/common.e2d71ce8.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__components__Explore__Recommend~p__explore__routers__Docs~p__explore__routers__Repos~p_~d6257766.aa1bcc43.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__components__Explore__Recommend~p__explore__routers__Docs~p__explore__routers__Repos~p_~d6257766.fac19d5b.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/c__Lakex~p__editor__routers__TextEditor.9defba11.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/c__Lakex~p__editor__routers__TextEditor.3a98afb8.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers.244d87f7.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers.ef3c862f.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/c__Lakex.acd5cec4.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/c__Lakex.653d1e93.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/layout__MainLayout.ae548301.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/layout__MainLayout.c0075e36.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__model.511a24e3.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers__EditCustomIndex.d4fbfe9e.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers__EditCustomIndex.28048163.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers__ShareExpired.8113c1a2.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers__ShareExpired.b6dff962.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers__SharePassword.1a6ae926.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__bookRepo__routers__SharePassword.f76c7685.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__components__Explore__Events.6d43e196.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__components__Explore__Events.979d04c6.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__components__Explore__Recommend.ab8c57cb.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__components__Explore__Recommend.ac025d9d.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__model.2d27d4bc.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__App.4d4a0a8c.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__App.08fcac15.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__CollabBooks.40627926.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__CollabBooks.91d8d56d.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Collects.0a516ca7.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Collects.b5f172fe.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Dashboard.5f89b7f3.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Dashboard.be7c1714.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Explore.b51bb073.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Groups.198f522b.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Groups.ad67b3b7.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__History.086ddd9c.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__History.5387e7a8.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__MyBooks.40627926.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__MyBooks.61608f6e.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Notes.a878e2d7.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Notes.ffe2cc7a.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Recycles.ab448ca1.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__dashboard__routers__Recycles.3434b09c.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__doc__model__page.424fcfd2.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__doc__routers.66f72a35.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__doc__routers.39267068.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__doc__routers__version.e7b71a05.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__doc__routers__version.186ff53b.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__model.7ef254a2.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__Asl.60282b53.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__Asl.fa585dad.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__TextEditor.f413dbfc.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__TextEditor.81c5d11d.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__board.591d841b.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__board.832f1003.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__doc.a1ccd84d.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__doc.e652cf65.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__embed.500645af.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__embed.743631c5.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__embed_extreme.5563bfd4.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__embed_extreme.88434cbe.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__sheet.8a86af45.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__sheet.2daf2fb0.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__show.75463f8e.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__show.14157f9c.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__table.60aad9c2.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__editor__routers__table.29a799ed.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__model.263db0b2.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Books.cfc93cd2.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Books.8ffd07d8.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Custom.710dc957.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Custom.604bf4aa.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Embed.daf129f3.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Embed.1a8cd333.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Error403.8113c1a2.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Error403.e426da8e.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Group.a1fbd1b1.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Group.aca6ba40.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Members.c73713ca.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Members.fc9d4e92.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Migrate.e821f2d6.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Migrate.c5718315.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Recycles.724821a4.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Recycles.9b99a94d.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Statistics.e849f2e3.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Statistics.e2b4dc68.async.js", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Upgrade.a42075c1.chunk.css", "https://gw.alipayobjects.com/os/chair-script/skylark/p__group__routers__Upgrade.d80c9df1.async.js", "https://gw.alipayobjects.com/os/lib/??react/16.13.1/umd/react.production.min.js,react-dom/16.13.1/umd/react-dom.production.min.js,react-dom/16.13.1/umd/react-dom-server.browser.production.min.js,moment/2.24.0/min/moment.min.js", "https://gw.alipayobjects.com/as/g/larkgroup/lake-codemirror/6.0.2/CodeMirror.js", "https://gw.alipayobjects.com/as/g/larkgroup/lark-sheet/11.0.20/lark-sheet.css", "https://gw.alipayobjects.com/a/g/lark/??immutable/3.8.2/immutable.min.js", "https://gw.alipayobjects.com/as/g/larkgroup/lark-sheet/11.0.20/lark-sheet.js"]; self.resourceBase = "https://gw.alipayobjects.com/os/chair-script/skylark/";self.addEventListener("install", (e => {//預加載常用資源Array.isArray(self.assets) && e.waitUntil(caches.open("v1").then((e => {e.addAll(self.assets)}))) })), self.addEventListener("activate", (e => {Array.isArray(self.assets) && caches.open("v1").then((e => {e.keys().then((t => {t.forEach((t => {//過期資源釋放self.assets.includes(t.url) || e.delete(t)}))}))})) })); const r = [self.resourceBase, "https://at.alicdn.com/t/", "https://gw.alipayobjects.com/os/"]; self.addEventListener("fetch", (e => {//攔截資源,滿足上述域名,優先使用緩存,否則使用網絡下載資源并更新資源。r.some((t => e.request.url.startsWith(t))) && e.respondWith(caches.match(e.request).then((t => t && 200 === t.status ? t : fetch(e.request).then((t => {if (200 !== t.status) return t;const r = t.clone();return caches.open("v1").then((t => {t.put(e.request, r)})), t})).catch((() => {}))))) }))緩存、緩存更新、攔截請求
// 緩存靜態資源文件列表 let cacheFiles = ['./test.js','./index.html','./src/img/yy.png' ] // serviceworker使用版本 let __version__ = 'cache-v2'// 緩存靜態資源 self.addEventListener('install', function (evt) {// 強制更新sw.jsself.skipWaiting()evt.waitUntil(caches.open(version).then(function (cache) {return cache.addAll(cacheFiles)})) })// 緩存更新 self.addEventListener('active', function (evt) {evt.waitUntil(caches.keys().then(function (cacheNames) {return Promise.all(cacheNames.map(function (cacheName) {if (cacheName !== version) {return caches.delete(cacheName)}}))})) })// 請求攔截 self.addEventListener('fetch', function (evt) {console.log('處理fetch事件:', evt.request.url)evt.respondWith(caches.match(evt.request).then(function (response) {if (response) {console.log('緩存匹配到res:', response)return response}console.log('緩存未匹配對應request,準備從network獲取', caches)return fetch(evt.request).then(function (response) {console.log('fetch獲取到的response:', response)// 必須是有效請求,必須是同源響應,第三方的請求,因為不可控,最好不要緩存if (!response || response.status !== 200 || response.type !== 'basic') {caches.open(version).then(function (cache) {cache.put(evt.request, response)})}return response;})}).catch(function (err) {console.error('fetch 接口錯誤', err)throw err})) })總結
以上是生活随笔為你收集整理的serviceWorker 服务器与浏览器之间的代理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【计算机架构】什么是云原生?云原生如何解
- 下一篇: Epicor 调试 customizat