Building a Search-Engine Optimized PWA with Angular
Making our Web App…Progressive!
It is quite easy to turn our app progressive in Angular 6. Simply run the following command in your terminal.
$ ng add @angular/pwa
This command will install the @angular/pwa
and @angular/service-worker
packages. It will also import the ServiceWorkerModule
in the app.module.ts
imports
array.imports: [ BrowserModule.withServerTransition({ appId: 'serverApp' }), HttpClientModule, AppRoutingModule, UiModule, ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }) ],
The src/manifest.json
file is where we can define how our PWA behaves when it gets installed on our user’s device.
{ "name": "Store", "short_name": "store", "theme_color": "#343a40", "background_color": "#fafafa", "display": "standalone", "scope": "/", "start_url": "/",}
In the head
tag of src/index.html
file, re-write the meta
tag for theme-color
by setting it to #343a40
.
<meta name="theme-color" content="#343a40">
Run the command npm run build && npm start
.
Service Worker
Service workers are used to help us run our application when the browser is in an offline mode. But if we go offline now, we will get a huge error in our dev tools because the app is still trying to download data from the API.
What we need to do is create a cache for the API and assets by configuring the Service Worker inside the ngsw-config.json
file. Lets define a new object called externals
inside the assetsGroup
array as shown below:
{ "name":"externals", "installMode":"prefetch", "updateMode":"prefetch", "resources": { "urls":[ "https://ajax.googleapis.com/**" ] } }
Similarly, create another object named images
.
{ "name": "images", "installMode": "prefetch", "updateMode": "prefetch", "resources": { "urls": [ "http://dc-rebirth.now.sh/images/**" ] }}
Below the assetsGroup
array, create another array called dataGroups
.
"dataGroups":[{ "name":"rest-api", "urls":[ "http://dc-rebirth.now.sh/api/**" ], "cacheConfig":{ "strategy": "freshness", "maxSize": 100, "maxAge": "1h", "timeout": "5s" } }]
There is only one scenario left that we need to take care of: Fallback content if JavaScript is not available.
Go to index.html
file and add a <no-script>
tag to the body.
<body> <noscript> <div class="alert alert-info"> View this page in JS </div> </noscript> <app-root></app-root></body>
SEO
To improve the SEO Score of our Angular App, create a new file called robots.txt
inside the src
folder. Inside, set the content to User-agent:*
, and Allow: /
.
Then open the angular.json
file, and inside the builds
object in the assets
array, add src/robots.txt
. Do the same for tests
object.