Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Wednesday, January 6, 2021

Service Worker


 

In this post we will review the Service Worker:


" A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction "


What are these "new doors"? Run a service worker, enables control over the network requests sent by the page to any server. The main goal of a service worker is to manage cache, so you have full control on the caching of the items, including the cache expiration. The service worker also enables some additional inspection of the requests and responses for any other purposes, e.g. logging, security, and more.

Notice: the service worker will be run only on SSL sites and on the localhost site (for development purposes).


To use a service worker add the following to the main page of the application.


index.html

if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/serviceworker').then(function (registration) {
}, function (err) {
console.log('ServiceWorker registration failed: ', err)
})
})
}



Then implement the service worker on its own file.


serviceworker.js

self.addEventListener('fetch', function (event) {
let response = event.request
if (shouldBeSent(url)) {
response = fetch(response)
} else {
response = getFromCache()
}
event.respondWith(response)
})




The service worker can use the caches API to return a response from the cache, or to save it to the cache. Notice however, that the service worker is just another layer above the browser cache API, so for example, if the service worker decides not to handle the fetch event, and run the standard fetch, you might still end up with getting the actual resource from the browser local cache.



Final Note


There are many articles explaining the lifecycle of a service worker, but for the most cases you don't really care much about it. The one item you do need to pay attention for is that the service worker will not be replaced as long as it serve a page, so if you're changing a service worker code, close all site tabs to allow the browser to use the new version.

An alternative is to use the chrome debug window, which is very useful for other purposes as well, and manually reload it:



No comments:

Post a Comment