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

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.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Sunday, September 30, 2018 in Blog, JavaScript

Unlimited Automated Page Speed Monitoring & Tracking. Completely free.
Use SpeedFactor to track your website. It’s simple, reliable, and best of all, it’s free forever.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles


Privacy Policy