How to add offline capabilities with service worker in angular

Author
April 06, 2022

In this article i will explain you how you can add offline capabilities using service worker in your angular application. Service worker is additional thread other than main javascript thread to handle offline capabilities it cache all the request so that if same request is made it returns from it’s cache

Step 1 Adding Angular service worker in to your angular application

In order to add service worker in your angular application run below command

ng add @angular/pwa

Now when you run below command it will create angular-pwa folder inside build folder

ng build --prod

Step 2 Check service worker locally

  • In order to check service worker locally in your angular application you need to install lightweight server run below command to install lightweight server
npm install -g http-server
  • Navigate to the dist folder cd dist/angular-pwa and run below command
http-server -p 8001

Step 3 Caching Assets for Offline Use

Go to ngsw-config.json file this is the main file through which you can configure your service worker and control which assets to cache or which to not

As you can see i have added some urls to cache under assetsGroups->urls array

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": ["/favicon.ico", "/index.html", "/*.css", "/*.js"],
        "urls": [
          "https://fonts.googleapis.com/css?family=Oswald:300,700",
          "https://fonts.gstatic.com/**"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": ["/assets/**"]
      }
    }
  ]
}

Step 4 Caching Dynamic Assets & URLs

In order to cache dynamic assets and url’s you need to add a new property array in your ngsw-config.json file that is dataGroups

As you can see in below json i have added a new property with name “dataGroups” in that array i have added API url

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": ["/favicon.ico", "/index.html", "/*.css", "/*.js"],
        "urls": [
          "https://fonts.googleapis.com/css?family=Oswald:300,700",
          "https://fonts.gstatic.com/**"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": ["/assets/**"]
      }
    }
  ],
  "dataGroups": [
    {
      "name": "posts",
      "urls": ["https://jsonplaceholder.typicode.com/posts"],
      "cacheConfig": {
        "maxSize": 5,
        "maxAge": "6h",
        "timeout": "10s",
        "strategy": "freshness"
      }
    }
  ]
}