How To Implement PWA Using Angular

Implement PWA using Angular


Ahead-of-Time(AOT) compilation

One way to make an Angular app load faster is to run its compiler under the AOT. i.e. the compiler only runs once during the build step only; the app does not need to compile when trying to load it in browser.


With Angular-cli, it is as simple as writing one command line statement.

ng build - -prod - -aot

And that’s it. Now, just run and check it, which will make your application 50% faster and also reduce the bundle size to 45% . Isn’t it awesome guys!!!


Service Worker


It is an entirely separate script file that runs in the background of your browser. We first need to register service worker before using it. We can do that by simply putting the below script into html.

[code language=”html”]  
<!doctype html>  
<html>  
 
<head>  
  <meta charset="utf-8">  
  <title>Pwa1</title>  
  <base href="/">  
 
  <meta name="viewport" content="width=device-width, initial-scale=1">  
  <link rel="icon" type="image/x-icon" href="favicon.ico">  
  <link rel="manifest" href="/manifest.json">  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" 
    crossorigin="anonymous">  
 
  <!-- Optional theme -->  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" 
    crossorigin="anonymous">  
 
</head>  
 
<body>  
  <app-root>Loading...</app-root>  
  <noscript>  
 
    <h4 style="font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica;">  
      Sorry, JavaScript needs to be enabled in order to run this application.  
    </h4>  
  </noscript>  
 
  <script>  
 if ('serviceWorker' in navigator) {  
      navigator.serviceWorker.register('/service-worker.js').then(function (registration) {  
 // Registration was successful 
        console.log('ServiceWorker registration successful with scope: ', registration.scope);  
      }).catch(function (err) {  
 // registration failed :( 
        console.log('ServiceWorker registration failed: ', err);  
      });  
    }  
  </script>  
</body>  
 
</html>  
 
[/code]  

This script will check if the browser supports Service Worker or not. If it supports service worker, it will register it. Now, we require service worker precache which will generate service worker module.


We can add sw-precache by simply writing

 npm install - - save-dev sw-precache

Now, in your package.json file, add precache script.

[code language=”javascript”]  
{  
 "name": "pwa1",  
 "version": "0.0.0",  
 "license": "MIT",  
 "scripts": {  
 "ng": "ng",  
 "start": "ng serve",  
 "build": "ng build",  
 "test": "ng test",  
 "lint": "ng lint",  
 "e2e": "ng e2e",  
 "precache": "sw-precache --verbose --config=sw-precache-config.js" 
  }  
 
[/code]  

And also, add the following file to root directory of you Angular project and name it as sw-precache-config.js, which contains information about what files are to be cached.

[code language=”javascript”]  
 
module.exports = {  
  staticFileGlobs: [  
 'dist/**.html',  
 'dist/**.js',  
 'dist/**.css',  
 'dist/images/*',  
 'dist/icons/*' 
  ],  
 root: 'dist',  
  stripPrefix: 'dist/',  
  navigateFallback: '/index.html',  
  runtimeCaching: [{  
    urlPattern: /rkdemotask\.herokuapp\.com/,     
    handler: 'networkFirst' 
  }]  
};  
 
 
[/code]  

Here, I am caching all HTML, CSS, and JS files to dist folder because when we run the production build with Angular cli, it generates the compiled and minified bundle in dist directory which we deploy and host on Server.


All done now. If we want to enable service worker, we need to follow the following steps.

  1. ng build - - prod - - aot

  2. npm run precache

Here, the second step will generate serviceworker.js file in our dist directory.

On first time load.


On repeated visit


App Manifest


We can give users "add to home screen" prompt in order to provide them mobile application feel. To do so, we only need to add JSON file inside our src directory. Before that, we need to do some adjustment in index.html as shown below.

<link rel="manifest" href="/manifest.json">  

And one more change in our .angular-cli.json file is needed. 

"assets": [  
 "assets",  
 "favicon.ico",  
 "manifest.json" 
         ],  

Finally, the manifest.json file

[code language=”javascript”]  
 
{  
 "name": "jinal shah",  
 "short_name": "jinal shah",  
 "icons": [  
    {  
 "src": "assets/icons/logo.png",  
 "sizes": "192x192",  
 "type": "image\/png" 
    }  
  ],  
 "display": "standalone",  
 "start_url": "./?utm_source=web_app_manifest" 
}  
 
[/code]   

We can even add splash screen in the manifest file.



































Hope this article will be helpful to you.


Source: C# Corner