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

πŸ‘‹ Ciprian on Sunday, September 30, 2018 in Blog, JavaScript
Last modified on Sunday, September 30, 2018

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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. Last modified on Sunday, September 30, 2018.

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy