Implement PWA using Angular
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!!!
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.
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.
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.
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.
ng build - - prod - - aot
npm run precache
Here, the second step will generate serviceworker.js file in our dist directory.
On first time load.
On repeated visit
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
We can even add splash screen in the manifest file.
Hope this article will be helpful to you.
Source: C# Corner