Logo

dev-resources.site

for different kinds of informations.

Turn your angular application into PWA through service worker

Published at
2/19/2020
Categories
angular
pwa
serviceworkers
Author
harshalshah26
Categories
3 categories in total
angular
open
pwa
open
serviceworkers
open
Author
13 person written this
harshalshah26
open
Turn your angular application into PWA through service worker

What is Service worker?

A Service worker is a script (JavaScript file) that runs in background and contributes in offline first web application development. A Service worker cannot directly interact with the webpage nor it can directly access the DOM. It runs on a different thread but can communicate with webpages through messages (Post Messages).

Service workers are fully asynchronous. They are working on a different thread that’s why they don’t block your application in any way.

APIs such as synchronous XHR and localStorage can’t be used inside a service worker.

Service workers are terminated when not in use and restored when required.

Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as fetch; it also includes resources referenced in HTML and even the initial request to index.html. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers.

Service Workers in Angular

Starting with version 5.0.0, Angular ships with a service worker implementation. Angular developers can take advantage of this service worker and benefit from the increased reliability and performance it provides, without needing to code against low-level APIs.

The Angular service worker's behavior follows that design goal:

Caching an application is like installing a native application. The application is cached as one unit, and all files update together.

A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible.

When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code.

Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready.

The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed.

To support these behaviors, the Angular service worker loads a manifest file from the server. The manifest describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed, the contents of the manifest change, informing the service worker that a new version of the application should be downloaded and cached. This manifest is generated from a CLI-generated configuration file called ngsw-config.json.

Why to add Service Worker in Angular application?

Simple answer of this question is, to convert your application to WPA (Web Progressive Application) which responds even when there is no network connection.

How to add Service Worker?

Adding Service workers in angular app is as easy as adding a module. You just need to run following command.

ng add @angular/pwa --project project-name

where project-name Is a name you already defined in your angular.json file.

The above command will do following code change in your angular project out of the box. You do not need to do anything.

1.Enables service worker build support in the CLI by installing related packages (‘@angular/pwa’ and ‘@angular/service-worker’). It also add those package in package.json file.

  1. Add following lines in index.html
  1. Add following line in app.module imports.

ServiceWorkerModule.register('ngsw-worker.js', { enabled: true })

  1. Create manifes.webmanifest file is src folder

  2. Create service worker configuration file called ngsw-config.json file in root folder

  3. Update angular.json file with following changes in configuration object.

"configuration": {

"production": {

    "serviceWorker": true,

     "ngswConfigPath": "ngsw-config.json"

}
Enter fullscreen mode Exit fullscreen mode

}

  1. Installs icon files to support the installed Progressive Web App (PWA).

How to debug Service Worker?

1.Build the project
ng build –prod

  1. Run the project with http-server
    http-server –port 8080 dist

  2. Go to localhost:8080 in browser. When you load first time with network, it will cached necessary resources(whatever you have mentioned in config file).

  3. Go to network , checked offline and make network unavailable. Refresh the page and observe the network tab. You will see little gear icon and in the initiator column, you will see initiated by service-worker.js file.

Another way to debug whether Service workers are working correctly or not:

To see the audits results, go to Audits in the developer tools of Google Chrome and run the audits. Audits will tell you whether your application satisfies all the criteria for PWA or not. If service workers are working correctly then you will see green dot next to following points:

  • Registers a service worker that controls page and start_url
  • Current page responds with a 200 when offline
  • start_url responds with a 200 when offline

Above three points are the proof that your service workers are working correctly.

See how easy to convert your angular application to PWA. Convert it today and let me know the feedback in comment.

serviceworkers Article's
30 articles in total
Favicon
Service Workers: Revolutionizing Modern Web Apps
Favicon
Building Progressive Web Apps in Angular (using pwafire)
Favicon
Leveraging Service Workers for Advanced Caching Strategies in PWA: A Deep Dive for Beginners
Favicon
Integrating the Cache API with Service Workers
Favicon
Service worker weirdness in Chrome
Favicon
When service workers met framesets
Favicon
JS Service Workers — An Introduction
Favicon
Service workers in create-react-app v4+
Favicon
Offline caching with serviceworkers
Favicon
Why is an external service via internet, e.g. web-push with GCM needed for service workers to push notifications?
Favicon
Stop Bundling Scripts for Better Web Performance
Favicon
Does dev.to ever just hang and not load for you?
Favicon
Service workers con Workbox 3, tu primera vez
Favicon
Recreando el Parqués/Parchis en ReactJS - Primera Parte
Favicon
Recreando el Parqués/Parchis en ReactJS - Segunda Parte
Favicon
Build a Better Web with Service Workers
Favicon
Turn your angular application into PWA through service worker
Favicon
How to Get Videos to Work in Safari With Gatsby and Service Workers
Favicon
Who's using Service Workers?
Favicon
My MVP that's PWA and SPA with just wordpress. I'm seeing 0.5s loads, would adding service workers improve performance?
Favicon
Let Users Know When You Have Updated Your Service Workers in Create React App
Favicon
Help: Should a new service worker force a refresh to update a PWA?
Favicon
Going offline with IndexedDB
Favicon
sw-tools, a library to rule the Service Workers
Favicon
How to optimize your JavaScript app by using service workers
Favicon
Progressive Web Apps: Caching Strategies
Favicon
Paying Attention while Loading Lazily
Favicon
Launching: Push Notifications For Everyone!
Favicon
What service workers are being used on dev.to and what do they do?
Favicon
Steam Roulette

Featured ones: