Skip to content

Commit

Permalink
Use custom service worker with Workbox
Browse files Browse the repository at this point in the history
  • Loading branch information
Joni Katajamäki committed Dec 13, 2019
1 parent 08ef149 commit 0b9c7ae
Show file tree
Hide file tree
Showing 6 changed files with 635 additions and 46 deletions.
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,15 @@
"husky": "3.1.0",
"prettier": "1.19.1",
"pretty-quick": "2.0.1",
"react-scripts": "3.2.0"
"react-scripts": "3.2.0",
"workbox-build": "^4.3.1",
"workbox-cli": "^4.3.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"build": "react-scripts build && yarn service-worker",
"service-worker": "workbox copyLibraries build/workbox 6& yarn update-sw",
"update-sw": "workbox injectManifest workbox.config.js",
"test": "react-scripts test --verbose",
"lint": "eslint src",
"eject": "react-scripts eject"
Expand Down
4 changes: 1 addition & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,5 @@ ReactDOM.render(
document.getElementById('root')
)

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()
serviceWorker.register()
38 changes: 38 additions & 0 deletions src/service-worker-template.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/* eslint-disable no-restricted-globals, no-undef */

// See Workbox docs in https://developers.google.com/web/tools/workbox/modules/workbox-sw

self.importScripts('/workbox/workbox-v4.3.1/workbox-sw.js')

workbox.setConfig({ modulePathPrefix: '/workbox/workbox-v4.3.1' })
//self.workbox.logLevel = self.workbox.LOG_LEVEL.verbose;

self.addEventListener('install', event => event.waitUntil(self.skipWaiting()))
self.addEventListener('activate', event =>
event.waitUntil(self.clients.claim())
)

// GENERATED FILES ARE INJECTED HERE BY build-service-worker.js
workbox.precaching.precacheAndRoute([])

// API calls precache
workbox.precaching.precacheAndRoute([
'https://pof-backend-staging.partio.fi/spn-ohjelma-json-taysi/?postGUID=86b5b30817ce3649e590c5059ec88921',
'https://pof-backend-staging.partio.fi/tag-translations-json/',
])

// app-shell
workbox.routing.registerRoute('/', new workbox.strategies.NetworkFirst())

// webfont-cache
const webFontHandler = new workbox.strategies.CacheFirst({
cacheName: 'webfont-cache',
cacheExpiration: {
maxEntries: 20,
},
cacheableResponse: { statuses: [0, 200] },
})
workbox.routing.registerRoute(
/https:\/\/fonts.googleapis.com\/.*/,
webFontHandler
)
56 changes: 28 additions & 28 deletions src/serviceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,39 +18,39 @@ const isLocalhost = Boolean(
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
)

export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
return
}

window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
const swUrl = `${process.env.PUBLIC_URL}/service-worker-default.js`

if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
checkValidServiceWorker(swUrl, config)

// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
)
})
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
registerValidSW(swUrl, config)
}
});
})
}
}

Expand All @@ -59,9 +59,9 @@ function registerValidSW(swUrl, config) {
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
const installingWorker = registration.installing
if (installingWorker == null) {
return;
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
Expand All @@ -72,64 +72,64 @@ function registerValidSW(swUrl, config) {
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
)

// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
config.onUpdate(registration)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
console.log('Content is cached for offline use.')

// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
config.onSuccess(registration)
}
}
}
};
};
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
console.error('Error during service worker registration:', error)
})
}

function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
const contentType = response.headers.get('content-type')
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
registerValidSW(swUrl, config)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
)
})
}

export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
registration.unregister()
})
}
}
12 changes: 12 additions & 0 deletions workbox.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = {
globDirectory: './build/',
globPatterns: ['**/*.{html,js,css,png,jpg,json}'],
globIgnores: [
'service-worker-default.js',
'service-worker.js',
'workbox-sw.js',
'index.html',
],
swSrc: './src/service-worker-template.js',
swDest: './build/service-worker-default.js',
}
Loading

0 comments on commit 0b9c7ae

Please sign in to comment.