How to Implement a Service Worker in Your Website and How to Create a Basic PWA

on in Methods, Events and Scopes
Last modified on

You definitely don’t need a plugin for this. Although there are plugins which help with creating a service worker and a progressive web application, here’s how to do it using vanilla JavaScript.

Add the following code to your main JS functions file:

if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
        navigator.serviceWorker.register('/sw.js').then(function (registration) {
            // Registration was successful
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function (err) {
            // Registration failed
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}

Add the following code to your root folder and name it sw.js:

var CACHE_NAME = 'cache-v1';
var urlsToCache = [
    '/',
];

self.addEventListener('install', function (event) {
    // Perform install steps
    event.waitUntil(
        caches.open(CACHE_NAME).then(function (cache) {
            console.log('Opened cache');

            return cache.addAll(urlsToCache);
        })
    );
});

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then(function (response) {
            // Cache hit - return response
            if (response) {
                return response;
            }

            return fetch(event.request);
        })
    );
});

That’s it! One less plugin to take care of things.

Related posts