Build Progressive Web Apps — Chapter 5

Service Worker dan Cache Technology

Jansutris Apriten Purba
Nov 30 · 9 min read
Service Workers Lifecycle


Service Worker Registration

Service Worker is a script that is run by the browser in the background, which is separate from other scripts on the web page of the browser. Service workers are written using the JavaScript programming language, but are called in a different way from JavaScript code in general. In our case study this time, the service worker acts as a regulator of the request path by sorting which assets are already in the cache to be used immediately, and which assets need to be requested first to the network.

Pre-cache Assets

In the service-worker.js file, write the code to cache the assets and supply the assets that are already cached so that they can be used in future page calls. To register assets in the cache, we use the Cache API from the browser, including caches.open() to open cache, caches.add() and cache.addAll() to store assets in the cache, and caches.match() to check whether the requested asset is already in the cache. The API cache is based on promises. If you are not familiar with promises, you can learn in the “Promise and Fetch API” chapter.

Registering Service Worker

Create a file named service-worker.js in the project folder. Leave blank first.

<script>
// REGISTER SERVICE WORKER
if ("serviceWorker" in navigator) {
window.addEventListener("load", function() {
navigator.serviceWorker
.register("/service-worker.js")
.then(function() {
console.log("Pendaftaran ServiceWorker berhasil");
})
.catch(function() {
console.log("Pendaftaran ServiceWorker gagal");
});
});
} else {
console.log("ServiceWorker belum didukung browser ini.");
}
</script>
Service Worker section

Saving Assets to Cache

Now we will write the service worker code in the service-worker.js file. Add the following code in the file:

const CACHE_NAME = "firstpwa";
var urlsToCache = [
"/",
"/nav.html",
"/index.html",
"/pages/home.html",
"/pages/about.html",
"/pages/contact.html",
"/css/materialize.min.css",
"/js/materialize.min.js",
"/js/nav.js"
];

self.addEventListener("install", function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(urlsToCache);
})
);
});
Cache Storage
Network tab

Using Assets from Cache

Add the following code to the service-worker.js file so the page uses assets that have been cached:

self.addEventListener("fetch", function(event) {
event.respondWith(
caches
.match(event.request, { cacheName: CACHE_NAME })
.then(function(response) {
if (response) {
console.log("ServiceWorker: Gunakan aset dari cache: ", response.url);
return response;
}

console.log(
"ServiceWorker: Memuat aset dari server: ",
event.request.url
);
return fetch(event.request);
})
);
});
service workers tab
Offline option

Removing Old Cache

What happens when we change the contents of an application page, or change the CSS code? Yup, you will not see any changes in the browser page because the application display uses assets from the cache. But if you activate the Update on reload option in the Service Workers panel in DevTools, all changes in content and assets will be updated into the cache every time we refresh the application page.

const CACHE_NAME = 'firstpwa-v1';
firstpwa-v1
self.addEventListener("activate", function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheName != CACHE_NAME) {
console.log("ServiceWorker: cache " + cacheName + " dihapus");
return caches.delete(cacheName);
}
})
);
})
);
});

Easyread

Easy read, easy understanding. A good writing is a writing that can be understood in easy ways

Jansutris Apriten Purba

Written by

Love Coding, Traveling, Watching Film & Music

Easyread

Easyread

Easy read, easy understanding. A good writing is a writing that can be understood in easy ways

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade