Angular service worker |
Service worker is an important script that runs in background and separate
from a web page which is used to manage caching in application.
We have various rich functionalities in today's applications like push
notification , background syncing and tracking network traffic etc which work
with service worker and where service worker plays a great role.
With service worker it is possible to let user access the web page in case if
the user loses the internet connection. we often face some problems while
browsing like "Internet connection lost" that may effect the user experience
of an application but with the help of pwa we avoid such
problems.
let's focus on how to install service worker in angular. We need to run a
command that will add all necessary stuff to make service worker work in
angular.
We don't to include or declare things manually angular cli does it itself. we
just need to run a command so open up your terminal.
ng add @angular/pwa
As I have a complete guide on how to install service worker and files this above
command adds in our application , you may
find here.
ngsw-config.json
ngsw-config.json is a configuration file that is in json format which
specifies the file and data url Service worker has to cache and update the
cached files. This file needs to be registered first in order to work on web
browser.
We must import this file app.module.ts so that web browser
may install the service worker file at background separated by web page.
Service worker will start caching once the installation process is done on web
browser.
After the installation process of service worker it will be in one of two
stages, either the it stay terminated and save memory or it will
handling caching of pages soon as you make network requests.
ngsw-config.json is a runtime script file of Angular service worker
that contains all the files need to be cached at runtime.
{
"$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)"
]
}
}
]
}
1. $schema
Schema file is basically referring to angular service worker schema for
ngsw-config.json file inside angular packages. it contains data types,
default values , properties etc.
2. index
This use to refer the index file or the application usually it is index.html
in angular. index.html file can be found inside the src directory.
3. assetGroups
In assetGroups ,there is an array that maintains such files our
application needs for caching such as css , js or third party CDN files and
that are need to be included in proper manner.
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/index.html",
"/*.css",
"/*.js"
]
}
}
]
A. installMode
installMode is used to let service worker know which resource are to be cached
initially in the app.
There are two install modes in angular service worker which have
different caching strategies let me explain them:
- prefetch
- lazy
prefetch
prefetch strategy tells service worker for caching all the listed resources in
current version of angular app. Resources which are not requested will also be
cached in this case.
This helps angular application to work offline as it
prefetches all resources of specific version of angular application.
lazy
lazy mode tells angular service worker to only cache resources when they are
requested. In this case resources which are never requested will never be
loaded or cached.
This mode can be very useful as it does not let angular service worker cache
assets every time. only the request assets will be cached.
B. updateMode
updateMode is here to handle the behavior of cache when a new version
of the application discovered.
It is simply checks for updates
in service worker file (ngsw-config.json) whenever a user opens or refreshes
the web page of an application.
Now service worker has an update for the app then it will be downloaded or
cached automatically
So whenever a user will open the page next time , he should get the updated
version of the app.
There are two strategies of updateMode
- prefetch
- lazy
prefetch is used to download and cache the resources automatically if it finds an update in service worker (ngsw-config.com).
lazy only download and cache the resource if the resource is requested to be downloaded. Normally it checks and waits for the resources to be requested then only update. The lazy mode for "updateMode" only valid if the installMode was lazy.
C. resources
resources let service worker know about the resource that needs to be
cached by their extensions, file path.
4. dataGroups
dataGroups handles the data requests like API's response or some other
dependencies etc. These are different resources than we have in assetGroups.
"dataGroups": [
{
"name": "testApp",
"urls": ["/api/endpoint/**"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 10,
"maxAge": "12h",
"timeout": "10s"
}
}
]
urls takes the API's we want to cache data from. On loading it will
download and cache all the data from given url or API's.
cacheConfig has the configuration of dataGroups like cache strategies
, size of cache data and how long data remains in cache.
- strategy (performance - Cache-First or freshness - Network-First).
- maxSize is for handling the cached responses for a group.
- maxAge is for cache lifetime can be in milliseconds(u), seconds (s), minutes (m), hour (h), day (d).
- timeout
5. navigationUrls
"navigationUrls": [
"/**",
"!/**/*.*",
"!/**/*__*",
"!/**/*__*/**"
]
This refers the URL's we need in Service worker for our progressive web app that is used to redirect to index file.Now here is a complete look to the working Progressive web app example, you can see the application in offline mode and also in the header section you can see the data was loaded from cache that means our Service worker is working successfully in offline mode.
Angular service worker |
Here is an example how we can verify if the service worker loads data from cache.(pwa example)
From cache memory in offline mode |
Summary
In this article, we focused on Service Worker configuration and knew how we can turn a new angular project into Progressive web app with service worker (ngsw-config.com) and take advantage of various advance features of today's generation's apps like offline mode, push notification etc.
Related Articles
0 Comments