Table of Contents
Let’s get started with a basic outline of PWA and Service Workers.
What is PWA?
What are Service Workers?
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. It includes features like push notifications and background sync. In the future, service workers might support things like periodic sync or geofencing. The core feature is the ability to intercept and handle network requests, including programmatically managing a cache of responses.
-Matt Gunt, Developers.google.com
How setup service workers in existing or new angular application?
Before you start integration the PWA in the angular application you have check your application is already enabled PWA or Not using chrome browser.
Choose Device & audits type and click Run audit button. It’s will show the audit detail result as shown in the below image.
The audit result will be displayed that there is no PWA at present. So, now I am going to implement the Progressive Web App to work. Navigate to install your application, install path and add the below command.
ng add @angular/pwa
Once executed the above command, you will get the manifest link in index.html file and automatically added ngsw-config.json file in the root directory.
Next, To enable the service worker & ngswConfigPath in angular.json file in under configurations Objects. Below config added automatically. If not you have to add it manually.
"serviceWorker": true, "ngswConfigPath": "ngsw-config.json"
To add the service worker module in app.module files as below.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ServiceWorkerModule } from '@angular/service-worker'; import { environment } from '../environments/environment'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
{ "$schema": "./node_modules/@angular/service-worker/config/schema.json", "index": "/index.html", "assetGroups": [ { "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**", "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)" ] } } ] }
Now, it is ready to check with PWA enabled application. The PWA has to work in the production build. This following comment used to create a production build.
ng build --prod
Once you create the production build, you will see the ngsw-worker.js file in the build.
How to run the production build in the local environment?
sudo npm install -g http-server
http-server -p 8080 <buid file directory>
Check if the PWA is enabled using the above-mentioned steps. The audits result will look like this.
The PWA service worker caches the static files in the local browser, so the application won’t break even if there is no internet connection.
How to catch the external URL using service workers?
In this case, I am using google font. The URL is added to the index.html file.
<link rel="manifest" href="manifest.webmanifest"> <link href="https://fonts.googleapis.com/css?family=Supermercado+One&display=swap" rel="stylesheet">
Disconnect the internet and check if the font is loading in your application. You can see the network tab in the inspect window in Chrome.
"urls": [ "https://fonts.googleapis.com/css?family=Supermercado+One&display=swap" ]
Once you add the above code, run the production build and verify the application working in both online & offline. Now the file is catched from the service worker.
How to catch the service API using service workers?
Usually, application service API works with the Internet connection. Only if the browser works well without the internet, you can catch the service API in service workers.
dataGroups : { name: string, urls: string[], version?: number; cacheConfig: { maxSize: number, maxAge: string, timeout?: string, strategy?: 'freshness' | 'performance'; }; }
Name is used to uniquely identifies for each service APIs. URLs are a collection array string. It’s used to specify the catching service APIs URLs. Version is used to maintain the API catching versions in the application. cache config is used to match requests that will be cached based on below params,
maxSize: number, maxAge: string, timeout?: string, strategy?: 'freshness' | 'performance';
Endpoint: https://jsonplaceholder.typicode.com/todos
"dataGroups": [ { "name": "todos", "urls": [ "https://jsonplaceholder.typicode.com/todos" ], "cacheConfig": { "maxSize": 5, "maxAge": "6h", "timeout": "10s", "strategy": "freshness" } } ]
Over to You
And also you can try working with the same commands and methods used in this blog. It is available HERE!
Looking for more Angular Tutorials? Visit our blog and Subscribe for exclusive & latest articles on development technologies.
If you lack clarity or have doubts, suggestions on this blog, feel free to tell us in the comment section below.