PWA — Web app with a mobile experience
The progressive web app uses modern web capabilities to deliver an app-like user experience — Addy Osmani
Why we need PWA?
Google found that more than 60% of internet users nowadays use the internet from mobile
Ok, but why users are using mobile instead of laptops or PCs!
The reasons are:
- Portability
- Cheap Hardware
- Easy access to the internet
- The increased number of services on the internet
So, PWA promises to enable web apps to load in a slow network and offline mode also and gives the users the same experience like native mobile apps.
What are the benefits of using PWA?
- Reliable
The app should be loading fast and interact smoothly with user interaction in low network speed like 2 G because Google found that 53% of the users leave the page if it took more than 3 seconds to load. - Fast
It makes the web app so fast and smoothes and the user can interact with the app smoothly. - Responsive
The app should fit in all different sizes of devices, the perfect web app should be like liquid which takes the shape of its vessel. - Installable
You can install the web app on mobile without taking a big size from the memory and it will look like the native apps and you will find the web app icon beside the native apps icons in the home screen - Splash Screen
PWA add splash screen when startup the app, this makes the PWA feel more like native apps. - Highly engage-able
The app should keep the users engaged so PWA provides features like push notifications, home screen icon, full-screen mode and offline-first app to glorify user engagement. - Linkable
You can share the app easily by sending the URL. - Discoverable
Manifest file and service workers allow the contents to be found through search engines.
* we will talk later about manifest and service workers* - Progressive
The PWA does not need to be handled in multiple platforms like IOS & android so we just create one app and this app will work for all platforms and all devices sizes - Safe
So the connection between you and the app is secured against any third parties trying to get access to your sensitive data.
Is PWA working only with particular frameworks?
PWA doesn’t need any framework to use you can use it with native JS or with any framework like React, Angular and Vue.
*** one of the questions that I asked myself when learning PWA is how the PWA working offline how it can load the page when there is no network from where it can get the data that it wants to load and the answer is it makes it like native apps so in native apps when you install the app you download all resources and UI components that it needs to load the app and that’s the same what PWA make so PWA downloads HTML, CSS and images files and save them in the browser cache so once the user opens the app without network the app will get all needed resources from the browser cache. ***
So what we need to create a PWA app?
1- Service Workers
2- Manifest JSON file
3- HTTPS
Now, Let’s talk about each component individually!
Service Workers
Service workers are javascript works as a proxy between the browser and the network and manage multiple stuff like push notifications, help to build offline apps using browser cache and background sync so you can do some stuff in offline mode and once the network back this stuffs will run automatically like Whatsapp native app if you are offline and send message it will not be sent and once network back it will be sent and to know more about Service workers visit this site https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API.
So, How service workers help to build offline apps?
To know how the service workers build offline apps you should know some cache strategies that will help you to build your app in offline mode.
Caching strategies
Bellow, you will find the normal request is the web page sends a request to the network then the network will respond if there is a connection to the internet.
and if there is no internet the user will see the famous dinosaur in chrome browsers.
Cache only
The main goal for this strategy to make the user able to see something when opening the app and this will be for the static apps.
Network Only
This strategy is the opposite of the cache only strategy and we always access the network and we use this strategy if we don’t need to make offline apps.
Stale while revalidate
As the cache only strategy, we use this strategy to do offline apps and get the data from the cache then update your page and after that make a new request to fetch new data and update the cache with the new version of this data for next time when the user opens the app.
Cache then network
This requires the page to make two requests, one to the cache, one to the network. The idea is to show the cached data first, then update the page when/if the network data arrives.
so like twitter once you open the app, it displays for you the cached data and behind the scene, it makes a request to fetch new data and then update the page directly with this new data.
and to know more about the other cache strategies you can visit this site The offline cookbook.
Now, let’s move to the second component of PWA components.
Manifest JSON File
The manifest JSON file is a JSON file that contains all information that the app will need like:
- App name
- App short name
- Start URL
- App splash screen
- App splash screen text
- App icons
- App background
- Theme colour
- Orientation
- Description
- Display
And this is a basic manifest file…
{
"name": "Users App",
"short_name": "User",
"description": "PWA users app",
"theme_color": "#2196f3",
"background_color": "#2196f3",
"display": "standalone",
"start_url": "/build/index.html",
"icons": [
{
"src": "./images/icon-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "./images/icon-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "./images/icon-128x128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "./images/icon-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "./images/icon-152x152.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "./images/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "./images/icons/icon-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "./images/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
or you can use an online generator to generate your manifest file like Firebase Manifest Generator
and to know more about manifest JSON file visit this site https://developer.mozilla.org/en-US/docs/Web/Manifest
The last part is the HTTPS
PWA is working only with secure protocols to make users data secured so unauthorized users can’t access their content.
And now we almost know everything about the PWA Now let’s talk about…
What is the difference between the PWA and native apps!
- The Memory
Because it does not require download PWA doesn’t take much memory from the mobile. - Working on any platform
PWA can work in any platform android, IOS or windows phone and you don’t need to handle the app for every platform like the native apps. - PWA updates automatically
PWA update automatically so if there is new feature released the user will not ask to update the app to get this feature but in native apps always in any update, the user should update the app. - Access mobile device features
The main issue in PWA that it can’t access all mobile features like calendar and Bluetooth but native apps can. - Price
PWA development is cheaper than creating a native app because you will build only one app will work for all platforms. - You don’t need to submit you PWA app in stores
Now let’s create our first PWA app together!
Open your favourite editor, for me, I will use Visual studio code.
then create a new folder in your desktop for example and name it PWA_APP
and inside it creates a folder and calls it build
and inside it creates 3 new folders css
, js
and images
and create a file forindex.html
inside the build folder too.
And inside css
folder create a new file styles.css
and inside js
folder create a new file main.js
and now the app folder will look like…
Now go to your index.html
file and add basic HTML tags and add your CSS file and js file aswell.
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<title>List of Countries</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/styles.css">
</head><body>
<script src="js/main.js"></script>
</body>
</html>
Now go to your terminal and go to your directory for example
cd Desktop/PWA_APP
And run the following command.
npm init -y
It will create for you package.json
file.
Now, open package.json
and remove the following code.
"test": "echo \"Error: no test specified\" && exit 1"
And replace it with the below code to run the app using http-server
"serve": "http-server -p 8080 build -c-1"
and if you don’t have http-server
you can install it using.
npm install http-server -g
Then run the app using htpp-server
it will look like a blank page so now let’s make a basic users list…
Then add some styles for the list inside styles.css
Then fetch users API inside main.js
and append this data inside the list
Then run the app using the same command http-server
and then open it on http://127.0.0.1:8080/build/index.html
Now, the app will look like…
Now let’s check our website in offline mode.
So open dev tools then click on the application and you will see service workers tab on the left side of the screen click on it then you will the service worker title on the right side of the screen and below it, you will see the offline checkbox so check it and refresh the page, it will look like…
Now we need to make our app works fine in offline mode and don’t display this dinosaur for our users.
And to do this with the simple way we can use Workbox from google and it’s JavaScript Libraries for adding offline support to web apps.
So, now open your terminal and install workbox using
npm i workbox-cli -g
After running this command we will have the workbox in our machine now we will run another command to select which files you will cache it.
workbox wizard
it will ask you Whit is the root of your web app?
So select build by clicking enter.
Then it will ask you to select which files and folder that you want to precache.
So click a
to select all these files css
, html
and js
then click enter.
Then it will ask you where would you like your service worker file to be saved.
Click enter to save it inside build/sw.js
.
Then it will ask you Where would you like to save these configuration options?
Click enter to save the configuration inside workbox-config.js
Now let’s use another command to generate our Service worker to let our app works offline, and this command is…
workbox generateSW
After running the above app you will notice that there is a new file added to the build folder and its name is sw.js
and we will not modify it for now.
Now we need to register our service worker to let the offline work.
And we will do this using the following code, and you should add it inside main.js
file inside js
.
if('serviceWorker' in navigator){
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js');
});
}
Now let’s open the dev tools and check the cache storage to check if our files cached or not.
And then let’s do the same steps as before to check it offline.
So open the app again and open the dev tools then select application tab then click on service worker tab in the left side and check the offline checkbox and refresh the page again it will look like…
And now the dinosaur will not appear anymore but till now the title only appears in the screen in offline mode so now we need to do something to display the cached data that appeared to the user before.
And to do that we need to create a new file src-sw.js
inside the root folder of the project.
And put inside it two lines for import storage googleapis and add custom adjustments.
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');// Custom Adjustmentsworkbox.precaching.precacheAndRoute([]);
Now let’s go to workbox-config.js
file and add a new property.
...
"swSrc": "src-sw.js"
...
After that, we need to run another command
workbox injectManifest
To add the new adjustments inside service worker file sw.js
.
And for saving the data that comes from the API we will need to add the following command inside src-sw.js
.
// To cache api data using cache first startegyworkbox.routing.registerRoute(
new RegExp('https://jsonplaceholder.typicode.com/users'),
workbox.strategies.cacheFirst()
);
So the src-sw.js
will look like
Now let’s run this command again workbox injectManifest
Then let’s see our application in offline mode
you will see the app is running well and display all cached data in offline mode
And if you opened cache storage and click on workbox-runtime-https…
you will see the cached data
Now after adding service workers and let the app work in offline mode let’s add the manifest file to add some info for the app.
So, let’s create a new file inside the build folder and name it manifest.json
and it will look like…
Then link it inside <head>
in index.html
<link rel="manifest" href="../manifest.json">
Conclusion
To see the full app files and structure you can click on the below link and clone it in your machine.