Posted by: Daniel Boterhoven on Sun May 23
You now have more websites that require running a number of background tasks in order to provide a more complete experience. One of the newest and most effective ways to achieve this is through the use of service workers.
A service worker is a type of background script. The script is separate from the website and it can run even when the site is not open. It allows for the functionality of features, even in an offline environment. Common uses for service workers include push notifications and geofencing. In the past, these features were not typically associated with web-based applications.
The main benefit in using service workers is that they allow for a level of control over the offline experience that is offered by the website. For many offline features, sites will go with AppCache, but there are limitations that make it less than ideal for some applications.
The way that service workers make for a better experience is that they provide an offline experience for the web app that is more like that of a native application. Even when the user is offline, the script runs in the background, and this allows the web app to maintain a higher level of functioning.
The first thing to understand is that the lifecycle of a service worker is separate from that of the website. If you want to install a service worker for your site, you need to register it through the page’s JavaScript. Upon registration, the browser will run the service worker install in the background.
While service workers can allow for a powerful range of actions, they do have certain prerequisites. The first thing to understand is that not all browsers support them. The list is growing, but there are some that do not allow for this type of script.
As an additional requirement, service workers can only be deployed through HTTPs. This is essentially a security measure. With all of the things that a service worker can do, it is important to ensure that the response is coming from a legitimate source.
As we mentioned earlier, the first step in using a service worker is registration. Without registration, the browser would not know where to find the service worker script.
Once the service worker is registered, any controlled page will trigger the install. With the install, the associated files are cached.
After the service worker is installed, it is ready to receive requests. As the user works on the site, the service worker will get the requests and search the cache for results. If the cache has a matching response, it will return the cached information. If there is no corresponding response in the cache, it will make a network request for the necessary information.
Service workers can be good for allowing potential users to access your web application even when they have no internet connection. In addition to that, they can work to add features that your site may need to run, even when the page is not open.
…
Subscribe for updates