Getting Started with Service Workers
There was a time when people only related the use of push notifications to mobile applications. Luckily, that time has passed. Now there are Service Workers which can help us implement push notifications in desktop applications, and open up websites even when you’re offline.
A Service Worker is a script that runs in the background. It doesn’t need a web page or user interaction in order to work. This means that it will run even when your website is not open, even if it can’t access the DOM directly (the DOM can use the
postMessage API to communicate with the Service Worker, though). Currently, they include features like push notifications and geofencing. It can also intercept and handle network requests, that is the feature that we’re going to use in this tutorial. To those of you who are curious about browsers support, I suggest to take a look here. As you’ll see, its implementation is still at an early stage.
In order to demonstrate how the network intercepting feature of Service Workers works, we’ll make a static website which runs even when the user is offline. You can find the whole demo of the website here.
Service Workers give you the control of a web page where you can programmatically select the components you want to cache. Keep in mind that it’ll run offline only on second or subsequent visits. The reason behind this behavior will be explained later in this tutorial.
One common problem that Service Workers have is that they only work in “secure origins” (HTTPS sites, basically) in line with a policy which prefers secure origins for powerful new features. However, even localhost is considered a secure origin, so developing on it is an easy way to avoid this error. If you prefer, you could also use GitHub Pages (as I did) since they’re served over HTTPs.
Continue reading %Getting Started with Service Workers%
LEAVE A REPLY
You must be logged in to post a comment.