How
To Register A Service Worker?
To install a service worker you need to kick
start the process by registering it in your page. This tells the browser where
your service worker JavaScript file lives.
You can call below register () every time a page loads without concern; the browser
will figure out if the service worker is already registered or not and handle
it accordingly.
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// If Registration
was successful
console.log('Success
Registration - ', registration.scope);
},
function(err) {
// If Registration
was failed!
console.log('Failed
Registration - ', err);
});
});
}
This code checks to see if the service worker API
is available, and if it is, the service worker at /sw.js is registered once the
page is loaded.
How
To Install a Service Worker?
After a controlled page kicks off the
registration process, let's shift to the point of view of the service worker
script, which handles the install event.
Example looks like -
self.addEventListener('install', function(event) {
// Perform install steps
});
Inside of our install callback, we need to take
the following steps -
ü Open
a cache.
ü Cache
our files.
ü Confirm
whether all the required assets are cached or not.
Example looks like -
var CACHE_NAME = 'my-site-cache-v1.0';
var urlsToCache = [
'/',
'/styles/site.css',
'/script/site.js'
];
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);
})
);
});
How
To Cache and return Requests?
After a service worker is installed and the user
navigates to a different page or refreshes, the service worker will begin to
receive fetch events.
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);
})
);
});
I hope you are enjoying with this post! Please
share with you friends!! Thank you!!!