Offline first with progressive web apps [ Part 1 / 3 ]

What are progressive web apps?

What does a service worker do?

The website we will transform into a progressive web app

cd server
npm install
npm start
The home screen of the Video Voter app
The Video voter app
npm install http-server -g
cd client
http-server

Let’s start transforming towards a progressive web app

if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js")
.then(function (registration) {
console.log("Service Worker registered with scope:",
registration.scope);
}).catch(function (err) {
console.log("Service worker registration failed:", err);
});
}

The service workers JavaScript file should be on the root of you website for now and not under the js folder. This has to do with the service workers scope. More info in this youtube video:

self.addEventListener("fetch", function(event) {
console.log("Fetch request for:", event.request.url);
});
The logging from our service worker

We will keep updating our service worker, but those changes will not be reflected in the browser because the old service worker is still active. This has to do with the life cycle of a service worker. For now go to developers tools → Application → Service Workers → Tick the checkbox ‘Update on reload’

Update service worker on reload
var responseContent =
"<html>" +
"<body>" +
"<style>" +
"body {text-align: center; background-color: #333; color: #eee;}" +
"</style>" +
"<h1>Video Voter</h1>" +
"<p>There seems to be a problem with your connection.</p>" +
"</body>" +
"</html>";

self.addEventListener("fetch", function(event) {
event.respondWith(
fetch(event.request).catch(function() {
return new Response(
responseContent,
{headers: {"Content-Type": "text/html"}}
);
})
);
});
The offline page

Conclusion part 1

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store