Maxim Salnikov
@webmaxru
My App
Azure Developer Technical Lead at Microsoft
Progressive web apps use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications.
Service Worker API
Web App Manifest
* but not everything**
** use progressive enhancement strategy
Web API Confluence
Not available in service worker:
My App
Define the set of assets required to show the minimum viable UI
Service worker
install: put the assets into Cache Storage
activate: clear Cache Storage from the previous app version assets
fetch: if the asset is in Cache Storage serve it from there. Otherwise — download and serve it (and cache it)
Build time
Register service worker the way it does not affect the app loading performance
Website/webapp
App
Service-worker
Browser/OS
Event-driven worker
Cache
fetch
push
sync
'install'
Parsed
Installing
Activating
Redundant
'activate'
Waiting
Active
self.addEventListener('install', (event) => {
// Put app's html/js/css to cache
})
self.addEventListener('activate', (event) => {
// Wipe previous version of app files from cache
})
self.addEventListener('fetch', (event) => {
if (event.request.url.indexOf('/api') != -1) {
event.respondWith(
// Network-First Strategy
)
} else {
event.respondWith(
// Cache-First Strategy
)
}
})
# Installing the Workbox Node module
$ npm install workbox-build --save-dev
// We will use injectManifest mode
const {injectManifest} = require('workbox-build')
// Sample configuration with the basic options
var workboxConfig = {...}
// Calling the method and output the result
injectManifest(workboxConfig).then(({count, size}) => {
console.log(`Generated ${workboxConfig.swDest},
which will precache ${count} files, ${size} bytes.`)
})
// Sample configuration with the basic options
var workboxConfig = {
globDirectory: 'dist/angular-pwa/',
globPatterns: [
'**/*.{txt,png,ico,html,js,json,css}'
],
swSrc: 'src/service-worker.js',
swDest: 'dist/angular-pwa/service-worker.js'
}
// Importing Workbox itself from Google CDN
importScripts('https://googleapis.com/.../workbox-sw.js');
// Precaching and setting up the routing
workbox.precaching.precacheAndRoute([])
[
{
"url": "index.html",
"revision": "34c45cdf166d266929f6b532a8e3869e"
},
{
"url": "favicon.ico",
"revision": "b9aa7c338693424aae99599bec875b5f"
},
...
]
{
"scripts": {
"build-pwa": "ng build --prod &&
node workbox-build-inject.js"
}
}
workbox.routing.registerRoute(
new RegExp('/api/'),
new workbox.strategies.NetworkFirst()
);
workbox.routing.registerRoute(
new RegExp('/images/'),
new workbox.strategies.CacheFirst({
plugins: [...]
})
);
Maxim Salnikov
@webmaxru
Maxim Salnikov
@webmaxru