Service Worker Enabled in an Angular Application

Introduction 

 
Let’s think about a scenario where you’re in a place with limited access to the internet. If you open any website, the only thing you’ll see is chrome’s dino game (if you’re using Google Chrome).
Chrome’s dino game
What if I said you can still check your website, even when you’re offline or have no internet. Yes, It’s possible using a service worker. 😍
 

What is a Service Worker?

 
Service Worker is a type of web worker. It is a client site programmable proxy between your web application & the outside world.
 
Precisely, it’s essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.
 
As the worker runs separately from the main thread of the application, they are independent of the application they are associated with. This means the service worked will run in the background, even if you’ve closed the application tab.
 

What can the service worker do?

  1. Cache network request to improve performance & provide offline content
  2. Push notification
    Browser push notifications are handled by the service worker
  3. Background Sync
    Store the input when the application is offline and sync it whenever it will be online
The service worker uses the browser’s cache and IndexedDB to store the data. That's why Service Worker only works in a secured origin, i.e. HTTPS.
 

How to enable Service worker in an Angular application?

 
In order to add a service worker in your application, first, create an angular application using angular CLI.
 
ng new ServiceWorkerApp
 
This command will create a basic angular application for you, then use the following command to add service worker package in it:
 
ng add @angular/pwa
 
To know more about Angular feel free to connect with me on Twitter and LinkedIn 💖
 
Also, connect with me on medium.com.


Similar Articles