sw-helper
This library provides an easy approach towards working with service worker, highly inspired from sw-toolbox
Install
npm install sw-helper --save
Usage
const prefetchFiles = 'css/modal.css'var cacheFiles = url: ".css" url: ".js" ;const strategy = 'cacheFirst' ;
And you are done!
Options
cacheName
This the name of the cache. Change the name when you want to flush all the resources cached by browser.
prefetchFiles : string[]
These are the files that should be cached as soon as page loads (Actually whenever service worker is installed).
const prefetchFiles = 'css/modal.css'
cacheFiles : Object[]
These are the files that should be cached whenever its first request is made.
cacheFiles
accepts regex too.
To cache all the js
files, use
const cacheFiles = url: ".*\\.js"
Options:
-
maxAgeSeconds: If resource is requested
maxAgeSeconds
after it was cached, it will be served directly from network.
Default value: Infinityconst cacheFiles =url: ".*\\.js"maxAgeSeconds: 86400 // 24 hours -
strategy: Caching strategy for the resource
const cacheFiles = url: ".*\\.js" strategy: 'cacheFirstUpdate'
Default value: The one globally defined
getKey : Function : Request => any
It is the function to specify key of the cache. If not specified, key is Request
const getKey = requesturl
To cache index.html i.e navigation request/document page, specify index.html
in cacheFiles
.
To cache all js files and index.html, use
const cacheFiles = ".*\\.js" 'index.html'
strategy
Currently following caching strategies are supported
cacheFirst
: Every time a resource is requested, it is served from cache if available, otherwise from network.cacheFirstUpdate
: Every time a resource is requested, it is served from the cache and then cache is updated in the background so that user gets the latest data next time.
PS - we will increase the list going forward.