Skip to content

Commit 5951508

Browse files
MikeyBeLikeXhmikosR
authored andcommitted
Pre-cache key assets with Workboxjs. (twbs#23533)
1 parent f5368ae commit 5951508

File tree

6 files changed

+2186
-284
lines changed

6 files changed

+2186
-284
lines changed

assets/js/src/pwa.js

+15
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,21 @@
77
window.addEventListener('load', function () {
88
navigator.serviceWorker.register('/sw.js').then(function (registration) {
99
console.log('ServiceWorker registration successful with scope: ', registration.scope)
10+
registration.onupdatefound = function () {
11+
var installingWorker = registration.installing
12+
installingWorker.onstatechange = function () {
13+
switch (installingWorker.state) {
14+
case 'installed':
15+
if (navigator.serviceWorker.controller) {
16+
console.log('new update available')
17+
location.reload(true)
18+
}
19+
break
20+
21+
default:
22+
}
23+
}
24+
}
1025
}).catch(function (err) {
1126
console.log('ServiceWorker registration failed: ', err)
1227
})

build/workbox.config.json

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"globDirectory": "./",
3+
"globPatterns": [
4+
"_gh_pages/**/*.{html,css,js,json,png,jpg}"
5+
],
6+
"swSrc": "./sw.js",
7+
"swDest": "./_gh_pages/sw.js"
8+
}

build/workbox.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const fs = require('fs')
2+
const path = require('path')
3+
const swBuild = require('workbox-build')
4+
const config = require('./workbox.config.json')
5+
const buildPrefix = '_gh_pages/'
6+
7+
const workboxSWSrcPath = require.resolve('workbox-sw')
8+
const wbFileName = path.basename(workboxSWSrcPath)
9+
const workboxSWDestPath = buildPrefix + 'assets/js/vendor/' + wbFileName
10+
const workboxSWSrcMapPath = `${workboxSWSrcPath}.map`
11+
const workboxSWDestMapPath = `${workboxSWDestPath}.map`
12+
13+
fs.createReadStream(workboxSWSrcPath).pipe(fs.createWriteStream(workboxSWDestPath))
14+
fs.createReadStream(workboxSWSrcMapPath).pipe(fs.createWriteStream(workboxSWDestMapPath))
15+
16+
const updateUrl = (manifestEntries) => manifestEntries.map((entry) => {
17+
if (entry.url.startsWith(buildPrefix)) {
18+
const regex = new RegExp(buildPrefix, 'g')
19+
entry.url = entry.url.replace(regex, '')
20+
}
21+
return entry
22+
})
23+
24+
config.manifestTransforms = [updateUrl]
25+
26+
swBuild.injectManifest(config).then(() => {
27+
const wbSwRegex = /{fileName}/g
28+
fs.readFile(config.swDest, 'utf8', (err, data) => {
29+
if (err) {
30+
throw err
31+
}
32+
const swFileContents = data.replace(wbSwRegex, wbFileName)
33+
fs.writeFile(config.swDest, swFileContents, () => {
34+
console.log('Pre-cache Manifest generated.')
35+
})
36+
})
37+
})

0 commit comments

Comments
 (0)