Leveraging service workers to enhance web app performance and reliability

Leader posted 3 min read

Reason to use service workers in a web application?

One of the primary reasons to use service workers in a web application is to enable the application to access push notifications. Here are some key points about this and other benefits of service workers:

Benefits of Using Service Workers

  1. Push Notifications:

    • Service workers allow web applications to receive push notifications from a server, even when the application is not actively running. This enables real-time communication with users, keeping them engaged with updates and alerts.
  2. Offline Capabilities:

    • Service workers can cache resources and API responses, allowing your application to function offline or with a poor network connection. This greatly enhances the user experience.
  3. Background Sync:

    • Service workers enable background synchronization, allowing the application to defer actions (like sending data to the server) until the user has a stable internet connection.
  4. Improved Performance:

    • By caching static assets and serving them from the cache, service workers can significantly speed up the loading times of your application, improving overall performance.
  5. Interception of Network Requests:

    • Service workers can intercept network requests and modify responses, allowing you to implement custom caching strategies or handle errors gracefully.
  6. Enhanced User Experience:

    • With features like push notifications, offline access, and faster load times, service workers contribute to a smoother and more engaging user experience.

In summary, while enabling push notifications is a significant reason to use service workers, their capabilities extend to improving offline functionality, performance, and overall user engagement in web applications.

To implement push notifications in an Angular project using service workers. This example will demonstrate how to set up a service worker, request notification permissions, and handle push notifications.

Install Angular's service worker package:

ng add @angular/pwa

It will add this package @angular/service-worker to package json.
This command will automatically configure your project with a service worker and update your angular.json file.

So, It will add and update these files

 manifest.webmanifest
 ngsw-config.json
 angular.json
 "assets": "src/manifest.webmanifest",

index.html
<link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">

Configure the Service Worker

Open the src/ngsw-config.json file and ensure it contains basic caching settings. Here's an example configuration:

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    }
  ]
}

Create a Service Worker for Push Notifications

Create a new file for the service worker logic. For example, create src/service-worker.js:

src/service-worker.js

self.addEventListener('push', (event) => {
  const data = event.data ? event.data.json() : {};
  const title = data.title || 'Default Title';
  const options = {
    body: data.body || 'Default body text.',
    icon: 'assets/icon.png', // Ensure you have an icon in this path
  };

  event.waitUntil(
    self.registration.showNotification(title, options)
  );
});

Update the Angular Component

In your Angular component, set up the logic to register the service worker and request push notifications.

src/app/app.component.ts

import { Component } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  constructor(private swUpdate: SwUpdate, private http: HttpClient) {
    this.checkForUpdates();
    this.requestNotificationPermission();
  }

  checkForUpdates() {
    if (this.swUpdate.isEnabled) {
      this.swUpdate.available.subscribe(() => {
        console.log('New version available. Update your app.');
      });
    }
  }

  requestNotificationPermission() {
    Notification.requestPermission().then((permission) => {
      if (permission === 'granted') {
        console.log('Notification permission granted.');
        // Subscribe for push notifications
        this.subscribeToPushNotifications();
      } else {
        console.error('Notification permission denied.');
      }
    });
  }

  subscribeToPushNotifications() {
    navigator.serviceWorker.ready
      .then((registration) => {
        const applicationServerKey = this.urlB64ToUint8Array('YOUR_PUBLIC_VAPID_KEY');
        registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: applicationServerKey,
        }).then((subscription) => {
          console.log('User is subscribed:', subscription);
          // Send subscription to your server for future notifications
        }).catch((err) => {
          console.error('Failed to subscribe the user: ', err);
        });
      });
  }

  urlB64ToUint8Array(base64String: string) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
      .replace(/-/g, '+')
      .replace(/_/g, '/');
    const rawData = window.atob(base64);
    return Uint8Array.from(rawData, (c) => c.charCodeAt(0));
  }
}

Backend implementation:

https://coderlegion.com/3274/power-up-your-app-with-server-sent-push-notifications

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Learn to build complete web apps by mastering both frontend and backend development technologies.

Sushant Gaurav - Jan 29

Role of Web Performance in the Web Architecture

Sunny - Jul 8

Web Performance Optimization with NgOptimizedImage in Angular

Sunny - Jun 9

I Tested the Top AI Models to Build the Same App — Here are the Shocking Results!

Andrew Baisden - Feb 12

Understanding Obfuscation In Javascript

Dhanush Nehru - Jan 12
chevron_left