Skip to content

Commit

Permalink
Pre-cache key assets with Workboxjs. (#23533)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeyBeLike authored and XhmikosR committed Sep 15, 2017
1 parent f5368ae commit 5951508
Show file tree
Hide file tree
Showing 6 changed files with 2,186 additions and 284 deletions.
15 changes: 15 additions & 0 deletions assets/js/src/pwa.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope)
registration.onupdatefound = function () {
var installingWorker = registration.installing
installingWorker.onstatechange = function () {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
console.log('new update available')
location.reload(true)
}
break

default:
}
}
}
}).catch(function (err) {
console.log('ServiceWorker registration failed: ', err)
})
Expand Down
8 changes: 8 additions & 0 deletions build/workbox.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"globDirectory": "./",
"globPatterns": [
"_gh_pages/**/*.{html,css,js,json,png,jpg}"
],
"swSrc": "./sw.js",
"swDest": "./_gh_pages/sw.js"
}
37 changes: 37 additions & 0 deletions build/workbox.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const fs = require('fs')
const path = require('path')
const swBuild = require('workbox-build')
const config = require('./workbox.config.json')
const buildPrefix = '_gh_pages/'

const workboxSWSrcPath = require.resolve('workbox-sw')
const wbFileName = path.basename(workboxSWSrcPath)
const workboxSWDestPath = buildPrefix + 'assets/js/vendor/' + wbFileName
const workboxSWSrcMapPath = `${workboxSWSrcPath}.map`
const workboxSWDestMapPath = `${workboxSWDestPath}.map`

fs.createReadStream(workboxSWSrcPath).pipe(fs.createWriteStream(workboxSWDestPath))
fs.createReadStream(workboxSWSrcMapPath).pipe(fs.createWriteStream(workboxSWDestMapPath))

const updateUrl = (manifestEntries) => manifestEntries.map((entry) => {
if (entry.url.startsWith(buildPrefix)) {
const regex = new RegExp(buildPrefix, 'g')
entry.url = entry.url.replace(regex, '')
}
return entry
})

config.manifestTransforms = [updateUrl]

swBuild.injectManifest(config).then(() => {
const wbSwRegex = /{fileName}/g
fs.readFile(config.swDest, 'utf8', (err, data) => {
if (err) {
throw err
}
const swFileContents = data.replace(wbSwRegex, wbFileName)
fs.writeFile(config.swDest, swFileContents, () => {
console.log('Pre-cache Manifest generated.')
})
})
})
Loading

0 comments on commit 5951508

Please sign in to comment.