PWA - service worker - Workbox(未完)

Get Started(開始)

  • 只有get請求才能cache緩存嗎?

Create and Register a Service Worker File(創建和注冊 Service Worker)

  • Before we can use Workbox, we need to create a service worker file and register it to our website.(在使用Workbox之前,我們需要創建一個服務工作者文件并將其注冊到我們的網站。)
<script>
if ('serviceWorker' in navigator) {// Use the window load event to keep the page load performant(使用窗口加載事件保持頁面加載性能)window.addEventListener('load', () => {navigator.serviceWorker.register('/service-worker.js');});
}
</script>
  • Looking in the “Application” tab in Chrome DevTools you should see your service worker registered.(在chrome devtools中的“application”選項卡中,您應該看到服務工作者已注冊。)
    • Click the “Update on reload” checkbox to make it easier to develop with your new service worker.(單擊 “Update on reload” 復選框,以便與新的 service worker 一起開發。)

1291563-20190619104241873-1835315086.png

Importing Workbox(導入工作框)

  • To start using Workbox you just need to import the workbox-sw.js file in your service worker.(要開始使用Workbox,只需在服務工作者中導入Workbox-sw.js文件。)
    • Importing workbox-sw.js will create a workbox object inside of your service worker, and that instance is responsible for importing other helper libraries, based on the features you use.(導入workbox-sw.js將在服務工作者內部創建一個workbox對象,該實例負責根據您使用的功能導入其他助手庫。)
    • Due to restrictions in the service worker specification, these imports need to happen either inside of an install event handler, or synchronously in the top-level code for your service worker.(由于 service worker 規范中的限制,這些導入需要在安裝事件處理程序內部或在服務工作者的頂級代碼中同步進行。?)
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); // 同步的if (workbox) {console.log(`Yay! Workbox is loaded ?`);
} else {console.log(`Boo! Workbox didn't load ?`);
}

Using Workbox

  • The easiest way to do this is to register a route with Workbox that will match any .js files that are requested, which we can do with a regular expression:(在Workbox中注冊一個路由,這里我們使用正則表達式去匹配請求的任何.js文件)
  • If we want our JavaScript files to come from the network whenever possible, but fallback to the cached version if the network fails, we can use the “network first” strategy to achieve this.(如果我們希望我們的javascript文件盡可能來自網絡,但是如果網絡失敗,我們可以回退到緩存版本,我們可以使用“network first”策略來實現這一點。)
workbox.routing.registerRoute(new RegExp('.*\.js'),new workbox.strategies.NetworkFirst()
);
  • Add this code to your service worker and refresh the page. If your web page has JavaScript files in it, you should see some logs similar to this:(在控制臺會有相應策略的打印提醒)

1291563-20190619110130665-1262464337.png

  • Workbox provides a few caching strategies that you can use.(Workbox提供了一些您可以使用的緩存策略。)
  • your CSS could be served from the cache first and updated in the background(可以先從緩存中提供CSS,然后在后臺進行更新。)
workbox.routing.registerRoute(// Cache CSS files./\.css$/,// Use cache but update in the background.new workbox.strategies.StaleWhileRevalidate({// Use a custom cache name.(使用自定義緩存名稱。?)cacheName: 'css-cache',})
);
  • your images could be cached and used until it’s a week old, after which it’ll need updating.(使圖像被緩存并使用一周,一周后才更新。)
workbox.routing.registerRoute(// Cache image files./\.(?:png|jpg|jpeg|svg|gif)$/,// Use the cache if it's available.(如果緩存可用,請使用它。)new workbox.strategies.CacheFirst({// Use a custom cache name.cacheName: 'image-cache',plugins: [new workbox.expiration.Plugin({// Cache only 20 images.(只有20個圖像)maxEntries: 20,// Cache for a maximum of a week.(最多一周的緩存。)maxAgeSeconds: 7 * 24 * 60 * 60,})],})
);

What Else Can Workbox Do?

  • Routing and caching strategies are performed by the routing and strategies modules, but there are plenty of other modules, each offering specific behaviors that you can use in your service worker.(路由和緩存策略是由路由和策略模塊執行的,但是還有許多其他模塊,每個模塊都提供可以在服務工作者中使用的特定行為。)

Precache Files(預緩存文件)

  • If you want your web app to work offline or there are assets you know can be cached for a long time, precaching is the best approach.(當需要離線使用網頁或有需要加載很久的資源時,使用預緩存)
  • Workbox provides an easy way to precache files, ensuring that as your service worker changes, the precached files are maintained efficiently, only downloading updated files and cleaning up after the service worker is made redundant.(Workbox提供了一種簡單的預緩存文件的方法,確保隨著服務工作者的更改,預緩存文件得到有效的維護,只下載更新的文件,并在服務工作者被冗余后進行清理。)
  • The above snippet will download the files /styles/index.0c9a31.css, /scripts/main.0d5770.js and /index.html during the service worker install event and create a route that serves these files directly from the cache.(上述代碼段將在ServiceWorker安裝事件期間下載文件/styles/index.0c9a31.css、/scripts/main.0d5770.js和/index.html,并創建直接從緩存為這些文件提供服務的路由。)
  • This list of files is normally generated using a tool that manages the versioning of files.(此文件列表通常使用管理文件版本控制的工具生成。)
workbox.precaching.precacheAndRoute(['/styles/index.0c9a31.css','/scripts/main.0d5770.js',{ url: '/index.html', revision: '383676' },
]);

Generating a Precache Manifest(生成預緩存清單)

  • Below is a list of tools that can generate this list of files.(下面是可以生成此文件列表的工具列表。)
    • Workbox Command Line Interface (CLI):Ideal for developers who are unfamiliar with Node or have simple needs.(非常適合不熟悉節點或有簡單需求的開發人員。)
    • workbox Build:Perfect for developers wanting to programmatically build the list in Node or are using Gulp for their build process.(非常適合希望以編程方式在節點中構建列表或在其構建過程中使用Gulp的開發人員。)
    • Workbox Webpack Plugin:Ideal for developers using webpack to build their project.(非常適合使用Webpack構建項目的開發人員。)

CLI(Precache Files with Workbox CLI)

Gulp or Node(Precache Files with workbox-build)

Webpack(Precache Files with Webpack)

  • 稍后

Route Requests(路由請求)

  • There are three ways developers can match a request with workbox-routing.(開發人員可以通過三種方式將請求與Workbox路由相匹配。)
    • A string.
    • A regular expression.(正則表達式。)
    • A callback function.(回調函數。)

Matching a Route with a String(將路由與字符串匹配)

  • The only thing to be wary of is that this would only match for requests on your origin. (這只會與源站上的請求匹配。)
workbox.routing.registerRoute('/logo.png',handler // 這里應該是處理程序,這個例子先用handler占個位置,以下同
);
  • Instead you’d need to define the entire URL to match.(匹配源之外的路徑,需要定義整個URL來匹配。)
workbox.routing.registerRoute('https://some-other-origin.com/logo.png',handler
);

Matching a Route with a Regular Expression(將路由與正則表達式匹配)

  • The regular expression provided is tested against the full URL.(提供的正則表達式根據完整的URL進行測試)
workbox.routing.registerRoute(new RegExp('\\.js$'),jsHandler
);workbox.routing.registerRoute(new RegExp('\\.css$'),cssHandler
);workbox.routing.registerRoute(new RegExp('/blog/\\d{4}/\\d{2}/.+'),handler
);
  • If we wanted a route that would match that general path pattern made against both same- and cross-origin requests, using a regular expression with a wildcard (.+)at the start is one approach:(如果我們想要一個路由與針對相同和跨源請求的常規路徑模式相匹配,那么在開始使用帶有通配符(.+)的正則表達式是一種方法:?不在頭部添加通配符,只能匹配同源的?)
workbox.routing.registerRoute(new RegExp('.+/blog/\\d{4}/\\d{2}/.+'),handler
);

Matching a Route with a Callback Function(將路由與回調函數匹配)

  • The callback will receive an object with the requests URL and the FetchEvent received in the service worker.(回調將接收一個對象,該對象具有在 service worker 中接收到的請求URL和FetchEvent。)
  • One thing to note is that if you return a value in the match callback, it’ll be passed into the handler callback as a params argument.(如果在matchFunction回調中返回一個值,它將作為params參數傳遞到處理程序回調handler中。)
const matchFunction = ({url, event}) => {// Return true if the route should match // 路由匹配則返回 truereturn false;
};workbox.routing.registerRoute(matchFunction,handler
);

——————————————————————

  • There are two ways you can handle a request:(有兩種方法可以處理請求:)
    • Use one of Workbox’s strategies provided by workbox.strategies.(使用Workbox.Strategies提供的Workbox策略)
    • Provide a callback function that returns a Promise that resolves to a Response(提供一個回調函數,該函數返回解析為響應的承諾?)

Handling a Route with a Workbox Strategy(使用 Workbox 策略處理路由)

  • Most routes can be handled with one of the built in caching strategies.(大多數路由都可以通過一種內置的緩存策略來處理。)
    • Stale While Revalidate(緩存優先,隨后更新):This strategy will use a cached response for a request if it is available and update the cache in the background with a response form the network. (If it’s not cached it will wait for the network response and use that). (如果請求可用,則此策略將使用緩存響應,并使用來自網絡的響應在后臺更新緩存。(如果沒有緩存,它將等待網絡響應并使用該響應)。)
    • Network First(網絡優先):This will try and get a request from the network first. If it receives a response, it’ll pass that to the browser and also save it to a cache. If the network request fails, the last cached response will be used.(這將嘗試首先從網絡獲取請求。如果它收到一個響應,它將把它傳遞給瀏覽器,并將其保存到緩存中。如果網絡請求失敗,將使用上次緩存的響應。)
    • Cache First(緩存優先,不更新):This strategy will check the cache for a response first and use that if one is available. If the request isn’t in the cache, the network will be used and any valid response will be added to the cache before being passed to the browser.(此策略將首先檢查緩存。如果請求不在緩存中,則將使用網絡,并在傳遞到瀏覽器之前將任何有效響應添加到緩存中。)
    • Network Only(強制網絡):Force the response to come from the network.(強制響應來自網絡。)
    • Cache Only(強制緩存):Force the response to come from the cache.
workbox.routing.registerRoute(match,new workbox.strategies.StaleWhileRevalidate()
);workbox.routing.registerRoute(match,new workbox.strategies.NetworkFirst()
);workbox.routing.registerRoute(match,new workbox.strategies.CacheFirst()
);workbox.routing.registerRoute(match,new workbox.strategies.NetworkOnly()
);workbox.routing.registerRoute(match,new workbox.strategies.CacheOnly()
);
  • With each strategy you can customize the behavior of the Route by defining a custom cache to use and / or adding plugins.(每個策略,您可以定義要使用的緩存名 和 添加插件來定制路由的行為。定義相同的緩存名會怎樣?有什么意義?一個緩存名可以保存一組緩存數據,不同的緩存名是為了保存同一個接口不同的返回數據嗎?)
  • These options are often needed to make it safer when caching requests (i.e. limiting how long they are cached or making sure the data used on a device is limited).(緩存請求時,通常需要這些選項以使其更安全。例如:限制緩存的時間或保存空間)
new workbox.strategies.StaleWhileRevalidate({// Use a custom cache for this route.(為此路由使用自定義緩存。)cacheName: 'my-cache-name',// Add an array of custom plugins (like workbox.expiration.Plugin).(添加一組自定義插件,例如 workbox.expiration.Plugin)plugins: [...]
});

Handling a Route with a Custom Callback(使用自定義回調處理路由)

  • you can provide an asyncfunction which returns a Response object.(傳入一個返回 Response 對象的Async Function來處理。)
    • Fetch API 的 Response 接口代表一次請求的響應數據
  • It'll be called with a parameter object containing url and event (the FetchEvent) properties.(它將接收 URL 和 fetchvent 事件對象)
const handler = async ({url, event}) => {return new Response(`Custom handler response.`);
};workbox.routing.registerRoute(match, handler);
  • One thing to note is that if you return a value in the match callback, it’ll be passed into the handler callback as a params argument.(如果在match回調中返回一個值,它將作為params參數傳遞到處理程序回調中。)
const match = ({url, event}) => {return {name: 'Workbox',type: 'guide',};
};const handler = async ({url, event, params}) => {// Response will be "A guide to Workbox"return new Response(`A ${params.type} to ${params.name}`);
};workbox.routing.registerRoute(match, handler);

Configure Workbox(配置Workbox)

Configure Cache Names(配置緩存名稱)

  • By default, Workbox will only create two caches, one for precaching and one for runtime caching. Using workbox-core you can get the current cache names like so:(默認情況下,Workbox將只創建兩個緩存,一個用于預緩存,另一個用于運行時緩存。使用Workbox Core,您可以獲得當前緩存名稱,如下所示:)
const precacheCacheName = workbox.core.cacheNames.precache;
const runtimeCacheName = workbox.core.cacheNames.runtime;
  • Both the precache and runtime cache names are made of three pieces of information:<prefix>-<cacheId>-<suffix>(預緩存和運行時緩存名稱都由三條信息組成:)
  • You can alter the cache names by altering all or some of these pieces of information:(可以通過更改以下信息來更改緩存名稱:)
  • We recommend changing the prefix for each of your projects. This allows you to work on multiple projects using the same localhost port number without mixing up the caches.(我們建議更改每個項目的前綴。這允許您使用相同的本地主機端口號處理多個項目,而不會混淆緩存。)
workbox.core.setCacheNameDetails({prefix: 'my-app',suffix: 'v1',precache: 'custom-precache-name',runtime: 'custom-runtime-name'
});

Custom Cache Names in Strategies(策略中自定義緩存名稱)

  • but it’s not uncommon to want additional caches for specific uses, such as a cache just for images.(需要額外的緩存用于特定用途并不少見,例如只用于圖像的緩存。)
  • In these cases, the cache name will be used exactly as you specify; the prefix and suffix will not be used.(在這些情況下,緩存名稱將完全按照您指定的方式使用。不會出現前綴和后綴)
  /\.(?:png|jpg|jpeg|svg|gif)$/,new workbox.strategies.CacheFirst({cacheName: 'my-image-cache',})
);

Custom Fetch Options in Strategies(策略中自定義提取選項)

  • you might find the need to customize some aspects of the outgoing requests.you can pass in a configuration value named fetchOptions to a strategy's constructor, corresponding to the init options used in the underlying Fetch API. (您可能會發現需要自定義傳出請求的某些方面。您可以將名為fetchOptions的配置值傳遞給策略的構造函數,對應于底層fetch api中使用的init選項。)
workbox.routing.registerRoute(new RegExp('https://third-party\\.example\\.com/'),new workbox.strategies.NetworkFirst({fetchOptions: {credentials: 'include',},})
);

轉載于:https://www.cnblogs.com/qq3279338858/p/11049843.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393159.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393159.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393159.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

draft.js_如何使用快捷方式在Draft.js中創建有序列表和無序列表

draft.jsby Andrey Semin通過安德烈塞米(Andrey Semin) 如何使用快捷方式在Draft.js中創建有序列表和無序列表 (How to create ordered and unordered lists in Draft.js with a shortcut) We at Propeller have encountered many differences between Draft.js and popular t…

當javaScript從入門到提高前需要注意的細節:變量部分

到了HTML5的時代&#xff0c;對javaScript的要求不是降低了&#xff0c;而是更提高了。javaScript語言的入門非常簡單&#xff0c;如果你有java、C#等C風格的結構化語言的基礎&#xff0c;那javaScript你最多半天就可以寫點什么了。但是javaScript是一種動態語言&#xff0c;這…

PAT乙級 1003. 我要通過!

題目&#xff1a; “答案正確”是自動判題系統給出的最令人歡喜的回復。本題屬于PAT的“答案正確”大派送 —— 只要讀入的字符串滿足下列條件&#xff0c;系統就輸出“答案正確”&#xff0c;否則輸出“答案錯誤”。 得到“答案正確”的條件是&#xff1a; 1. 字符串中必須僅有…

電臺復活節_如何通過在控制臺中隱藏復活節彩蛋使您的應用程序用戶驚訝

電臺復活節by Ethan Ryan由伊桑瑞安(Ethan Ryan) 如何通過在控制臺中隱藏復活節彩蛋使您的應用程序用戶驚訝 (How to surprise your app’s users by hiding Easter eggs in the console) I love console.logging(“stuff”).我喜歡console.logging(“ stuff”)。 I do it th…

leetcode1267. 統計參與通信的服務器(dfs)

這里有一幅服務器分布圖&#xff0c;服務器的位置標識在 m * n 的整數矩陣網格 grid 中&#xff0c;1 表示單元格上有服務器&#xff0c;0 表示沒有。 如果兩臺服務器位于同一行或者同一列&#xff0c;我們就認為它們之間可以進行通信。 請你統計并返回能夠與至少一臺其他服務…

System類入門學習

第三階段 JAVA常見對象的學習 System類 System類包含一些有用的字段和方法&#xff0c;他不能被實例化 //用于垃圾回收 public static void gc()//終止正在運行的java虛擬機。參數用作狀態碼&#xff0c;根據慣例&#xff0c;非0表示異常終止 public static void exit(int stat…

gulpfile php,Laravel利用gulp如何構建前端資源詳解

什么是gulp&#xff1f;gulp是新一代的前端項目構建工具&#xff0c;你可以使用gulp及其插件對你的項目代碼(less,sass)進行編譯&#xff0c;還可以壓縮你的js和css代碼&#xff0c;甚至壓縮你的圖片&#xff0c;gulp僅有少量的API&#xff0c;所以非常容易學習。 gulp 使用 st…

ios jenkins_如何使用Jenkins和Fastlane制作iOS點播構建系統

ios jenkinsby Agam Mahajan通過Agam Mahajan 如何使用Jenkins和Fastlane制作iOS點播構建系統 (How to make an iOS on-demand build system with Jenkins and Fastlane) This article is about creating iOS builds through Jenkins BOT, remotely, without the need of a de…

菜鳥也學hadoop(1)_搭建單節點的hadoop

其實跟官方的教程一樣 只是 我想寫下來 避免自己搞忘記了&#xff0c;&#xff0c;&#xff0c;&#xff0c;好記性不如爛筆頭 首先確認自己是否安裝了 java&#xff0c; ssh 以及 rsync 沒有裝的直接就 apt-get install 了嘛&#xff0c;&#xff0c;&#xff0c;java的不一定…

SP703 SERVICE - Mobile Service[DP]

題意翻譯 Description   一個公司有三個移動服務員。如果某個地方有一個請求&#xff0c;某個員工必須趕到那個地方去&#xff08;那個地方沒有其他員工&#xff09;&#xff0c;某一時刻只有一個員工能移動。只有被請求后&#xff0c;他才能移動&#xff0c;不允許在同樣的位…

CF758 D. Ability To Convert 細節處理字符串

link 題意&#xff1a;給定進制數n及一串數字,問在此進制下這串數能看成最小的數&#xff08;10進制&#xff09;是多少&#xff08;如HEX下 1|13|11 475&#xff09; 思路&#xff1a;此題要仔細思考細節。首先要想使數最小那么必定有個想法是使低位的數盡可能大即位數盡可能…

java 可能尚未初始化變量,java - 局部變量“變量”可能尚未初始化-Java - 堆棧內存溢出...

我得到這個錯誤。線程“主”中的異常java.lang.Error&#xff1a;未解決的編譯問題&#xff1a;rgb2無法解析為變量它總是導致錯誤的rgb2數組。 如何解決這個問題呢&#xff1f;BufferedImage img1 ImageIO.read(file1);BufferedImage img2 ImageIO.read(file2);int w img1.…

leetcode1249. 移除無效的括號(棧)

給你一個由 ‘(’、’)’ 和小寫字母組成的字符串 s。 你需要從字符串中刪除最少數目的 ‘(’ 或者 ‘)’ &#xff08;可以刪除任意位置的括號)&#xff0c;使得剩下的「括號字符串」有效。 請返回任意一個合法字符串。 有效「括號字符串」應當符合以下 任意一條 要求&…

軟件工程——個人課程總結

軟件工程&#xff0c;我就是沖著軟件這兩個字來的&#xff0c;開始我覺得我們大多數人也是這樣的&#xff0c;能開發一款屬于自己的軟件應該是我們人生中的第一個小目標八&#xff0c;在上學期學完java語言后&#xff0c;我們自認為自己已經具備了開發一款小軟件的能力&#xf…

規則網絡_實用的網絡可訪問性規則

規則網絡by Tiago Romero Garcia蒂亞戈羅梅羅加西亞(Tiago Romero Garcia) 實用的網絡可訪問性規則 (Pragmatic rules of web accessibility that will stick to your mind) I first started to work with web accessibility back in 2015, at an American retail giant. It h…

8-python自動化-day08-進程、線程、協程篇

本節內容 主機管理之paramiko模塊學習 進程、與線程區別python GIL全局解釋器鎖線程語法join線程鎖之Lock\Rlock\信號量將線程變為守護進程Event事件 queue隊列生產者消費者模型Queue隊列開發一個線程池進程語法進程間通訊進程池 轉載&#xff1a;  http://www.cnblogs.co…

部署HDFS HA的環境

> 環境架構部署規劃&#xff1a; bigdata1 NameNode ResourceManager Zookeeper JournalNode failOverController bigdata2 NameNode ResourceManager Zookeeper JournalNode failOverController bigdata3 DataNode NodeManager Zookeeper bigdata4 DataNode NodeManager &g…

php layui 框架,Thinkphp5+Layui高顏值內容管理框架

Thinkphp5Layui高顏值內容管理框架TP5Layui高顏值內容管理框架&#xff0c;新增API模塊Thinkphp5Layui響應式后臺權限管理系統專注打造好用的框架&#xff0c;極速開發&#xff0c;高效靈活&#xff0c;從架構上兼顧系統復雜度的迭代與需求多變。代碼結構清晰&#xff0c;接口開…

leetcode657. 機器人能否返回原點

在二維平面上&#xff0c;有一個機器人從原點 (0, 0) 開始。給出它的移動順序&#xff0c;判斷這個機器人在完成移動后是否在 (0, 0) 處結束。 移動順序由字符串表示。字符 move[i] 表示其第 i 次移動。機器人的有效動作有 R&#xff08;右&#xff09;&#xff0c;L&#xff…

在Angular專家Dan Wahlin的免費33部分課程中學習Angular

According to the Stack Overflow developer survey 2018, Angular is one of the most popular frameworks/libraries among professional developers. So learning it increases your chances of getting a job as a web developer significantly.根據2018年Stack Overflow開…