PWA and AMP: Getting the Best out of Both Worlds

How to combine PWA and AMP to build feature-rich and blazingly fast mobile web applications

Chameera Dulanga
Bits and Pieces

--

Photo by Massimo Sartirana on Unsplash

Progressive Web Apps (PWAs) are known for the rich feature set for web and mobile apps. On the other hand, as the name suggests, Accelerated Mobile Pages (AMPs) helps to build blazing fast mobile-friendly web sites.

But what if we combine them? Can we gain the best out of both worlds?

To find out more, let’s understand the strengths and weaknesses of these two technologies at first.

PWA — Providing Native User Experience for Web Apps

If you look at PWA at its core, these are a basic set of web technologies, smartly combined to give a better user experience to end-users. When it comes to mobile devices, using a PWA will help to provide some advanced features like offline support, background syncing, caching content, push notifications bundled to your web app. Since these features provide a rich user experience, it becomes comparable with native mobile apps.

It also goes to the next level by allowing the users even to install PWA shortcuts to their mobile home screen. Since web browsers put tight constraints on websites loaded there, it also ensures that the PWA stays lightweight and does not eat up your storage, memory, and CPU.

Some of you might wonder, is PWA slow compared to AMP since it provides these advanced features? It won’t be the case if you keep your PWA footprint small and efficient. Since PWA is designed to provide a better user experience, the requirement for performance comes without saying.

And I have seen some people arguing that since PWA uses JavaScript, it is slow. ( <- This is wrong)

There is a hidden misconception that PWAs require lots of JavaScript, and you need frameworks or libraries like Angular, React, or VueJS to build them. This is not true.

PWA is a web site or application served via HTTPS with a valid web manifest file, registered service worker with a fetch event handler.

As you can see, we can build feature-rich, faster web apps that give a native-like experience with PWA.

Then you might wonder, do we need AMP since PWA already takes care of most of the challenges?
Without jumping the gun, let’s first see the values AMP brings into web apps.

Tip: Share your reusable components between projects using Bit (Github).

Bit makes it simple to share, document, and reuse independent components between projects. Use it to maximize code reuse, keep a consistent design, collaborate as a team, speed delivery, and build apps that scale.

Bit supports Node, TypeScript, React, Vue, Angular, and more.

Example: exploring reusable React components shared on Bit.dev

AMP — Brings the Speed & Performance for Mobile Websites

The main focus of AMP is to provide faster mobile pages. Since Google started to penalize slow pages with SEO ranking, developers were looking for ways to build faster websites. And a unique solution also came from Google, which is known as Accelerated Mobile Pages.

As the name suggests, Accelerated Mobile Pages mainly focuses on the web pages’ speed and performance. AMP puts restrictions over the HTML, CSS, and JavaScript that a developer could embed into a page to increase page rendering speeds.

These restrictions are quite tight for JavaScript, where it’s not allowed on most occasions.

Besides, it also limits advanced features and interactive designs in AMPs. So, AMPs alone will not be suitable for apps with complex requirements and designs.

SEO support adds another layer of icing on top of this since Google loves these accelerated mobile pages, and they rank AMPs at the top of search results.

Although AMP has this fantastic speed and performance, it was not popular as PWA. One of the main reasons behind this unpopularity is AMPs’ limited set of features. In the beginning, AMP was just simple HTML, and there was no room for advanced functionalities. Being aware of that, AMP has started to provide some extra features to its users lately.

Components like amp-script allow using custom JavaScript inside AMP, components to combine with PWA features, and JavaScript Frameworks are some of them.

Did you know that we can use AMP and PWA in combination? This answer may confuse you because there is a conflict between using JavaScript within these two technologies. So, let’s dive a bit more deeply into this case.

Should we Combine AMP and PWA?

As we discussed earlier, both PWA and AMP are distinct from each other, and they achieve a separate set of objectives. AMP’s uniqueness lies within the lightning-fast speed, while PWA provides features like working offline, push notification, and caching. But the caching mechanism of PWA is not as powerful as the AMPs optimizations for the first load.

Furthermore, there are scenarios where we can combine these two to get the best out of both worlds.

1. AMP with PWA Features

You can combine AMP and PWA very easily if your product content is static and functionality is limited. In such scenarios, you can build AMP as a PWA and achieve a lightning-fast experience. However, the outcome will be a fully AMP charged PWA, alongside PWA features like service worker, offline access, etc.

2. AMP as Entry Point

Since AMP promises instant delivery for your application, using AMP as the entry point to your site will increase user interactions. Since AMPs are more focused on SEO and speed, your web app will attract more users and then redirect them into your PWA.

3. PWA as the Shell of AMP

Although I said that combining AMP and PWA is more suitable for apps with limited functionality, there are cases where it fits for advanced functionality. You can build your application’s shell with PWA and use AMP within that shell in such cases. This form of AMP is also known as Shadow AMP, and you can find a demo created by Google named ShadowReader from here.

Combing PWA with AMP Step by Step

Step 1: Let’s start with an AMP

You can start the development process by concentrating on entry points or landing pages, deciding where you would expect the maximum incremental improvements from AMP’s speed. The main reason for having AMP is its quick loading time when served from Google Cache. Sample AMP code of index.html file is shown below, and if you are new to AMP, you can use their boilerplate generator to get started.

<!doctype html>
<html amp lang="en">
<head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<title>Building a AMP as PWA</title>
<meta name="viewport"
content="width=device-width,minimum-scale=1,initial-scale=1">
<meta name="description"
content="Sample AMP as PWA News Website" />
<style amp-boilerplate>

</style>
</head>
<body>
<h2>Building a AMP as PWA</h2>
<amp-img alt="Image"
src="./images/banner.jpg"
width="720"
height="353"
layout="responsive">
</amp-img>
<div>
<p>Chameera Dulanga</p>
<p>medium.com</p>
<p>https://chameeradulanga.medium.com/</p>
</div>
</body>
</html>

Step 2: Enabling PWA Features

Most of the PWA features can be integrated into the AMP using service workers, and as the next step, you need to create a service worker with the required features. The following example shows a simple service worker with options for asset caching and offline working. Also, it is possible to create custom service workers too.

importScripts('https://cdn.ampproject.org/sw/amp-sw.js');
AMP_SW.init({
assetCachingOptions: [{
regexp: /\.(png|jpg|woff2|woff|css|js)/,
cachingStrategy: 'CACHE_FIRST',
}],
offlinePageOptions: {
url: '/offline.html',
assets: [],
},
});

Then you need to register the service worker using a separate HTML file, and due to security reasons, your service worker file must be served through HTTPS or localhost:

<!doctype html>
<title>installing service worker</title>
<script type=’text/javascript’>
if(‘serviceWorker’ in navigator){
// Register service worker navigator.serviceWorker.register(‘<PATH-TO-SERVICE-WORKER FILE>’).then(function(reg){
console.log(“SW registration succeeded. Scope is “+reg.scope);
}).catch(function(err){
console.error(“SW registration failed with error “+err);
});
}
</script>

Similarly, If you want to integrate “add to home screen” functionality to your website, you can easily create a manifest.json file and import that to the index.html file.

{
“short_name”: “AMP as PWA”,
“name”: “AMP as PWA Personal WebSite”,
“start_url”: “index.html”,
“icons”: [
{
“src”: “icons/icon-192.png”,
“type”: “image/png”,
“sizes”: “192x192”
},
{
“src”: “icons/icon-512.png”,
“type”: “image/png”,
“sizes”: “512x512”
}
],
“background_color”: “#D6DCDF”,
“theme_color”: “#D6DCDF”,
“orientation”: “portrait”,
“display”: “standalone”
}

You need to include this JSON file into the index.html file as well.

Step 3: Integrating Service Worker with AMP

AMP has introduced a component named amp-install-service worker, and we can use that component to install the service worker we created in the previous step. First, you need to include the amp-install-service-worker into the header section. It then provides an HTML tag with the iFrame option and can import the service-worker.html file to the index.html file using it.

Below code snippet shows a simple AMP page with amp-install-service worker installed:

<!doctype html>
<html amp lang="en">
<head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async
custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js">
</script>
<title>Building a AMP as PWA</title>
<meta name="viewport"
content="width=device-width,minimum-scale=1,initial-scale=1">
<meta name="description"
content="Sample AMP as PWA News Website" />
<link rel="manifest" href="/manifest.json"></head>
<body>
<h2>Building a AMP as PWA</h2>
<amp-install-serviceworker src="/sw.js"
data-iframe-src="install-sw.html"
layout="nodisplay">
</amp-install-serviceworker>


<amp-img alt="Image"
src="./images/banner.jpg"
width="720"
height="353"
layout="responsive">
</amp-img>
<div>
<p>Chameera Dulanga</p>
<p>medium.com</p>
<p>https://chameeradulanga.medium.com/</p>
</div>
</body>
</html>

Summary

Although there are some significant differences between APM and PWA, it is possible to combine them to get the maximum from both technologies. There are several methods you can combine PWA and AMP to optimize the performance of your application. In this article, I’ve explained only one approach that you could use as a reference.

If you wonder when to use it, This combination is well suited for applications that deal with content and has the requirements like offline working and push notifications.

Thank you for Reading !!!

--

--