A JavaScript service worker is a piece of JavaScript script that runs in the background of your browser, completely separated from the browser, to activate features that don’t require user attention. Service workers are delivering cool services like push notification, loading and syncing data on load. But the best feature, in my opinion, is providing offline experience for WPA.
In order to implement service workers, we need to install a service worker first by registering service worker with your app page. At installation step typically static assets are cached. The trick with caching static stuff is that it will fail if a resource is missing.
After install, you need to clear old cache before activating the service worker. When a service worker is activated it can either be terminated to save browser memory or handle fetch functions.
var cacheName = 'weatherPWA-v1'; var filesToCache = [ /*static resources go here*/ ]; self.addEventListener('install', function(e) { console.log('[ServiceWorker] Install'); e.waitUntil( caches.open(cacheName).then(function(cache) { console.log('[ServiceWorker] Caching app shell'); return cache.addAll(filesToCache); }) ); }); self.addEventListener('activate', function(e) { console.log('[ServiceWorker] Activate'); e.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (key !== cacheName) { console.log('[ServiceWorker] Removing old cache', key); return caches.delete(key); } })); }) ); }); self.addEventListener('fetch', function(e) { console.log('[ServiceWorker] Fetch', e.request.url); e.respondWith( caches.match(e.request).then(function(response) { return response || fetch(e.request); }) ); });
and remember to add the service worker into your app.js
if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/service-worker.js') .then(function() { console.log('Service Worker Registered'); }); }
Comments 3
I was looking for a good intro on service workers and I found your website. thanks Ramin Ahmadi
Great beat ! I would like to apprentice while you amend your website, how can i subscribe for a weblog web site? The account aided me a appropriate deal. I had been a little bit acquainted of this your broadcast provided brilliant clear idea
Good day! Would you mind if I share your blog with my zynga group? There’s a lot of people that I think would really appreciate your content. Please let me know. Thanks