Welcome Back Folks! Came again with another new blog.
If you are struggling with a storage problem in your mobile, then PWA is a saviour.
Let’s begin.. 😊
“A Progressive Web App (PWA) uses modern web capabilities to build Mobile Experience without getting to the App store.”
Progressive Web Apps are web applications that load in a web browser just like web pages or websites. It gives you a rich mobile experience via native-like functionalities such as ability to work offline, push notifications, and device hardware accessibility.
It feels like a native app and offers the same experience as a native one. There is no need to download it from an app store. It loads, runs, and functions in a web browser.
Progressive Web Apps Promote Mobile-First Approach
According to one Statista report,
The number of mobile phone uses is forecasted to reach 4.68 billion by 2019.
Going further, in 2016, an estimated 62.9 percent of the population worldwide already owned a mobile phone. This will round up to 67 percent by 2019.
This represents a clear picture of the mobile-first approach everywhere. The rise of mobile apps also denotes the ‘app-for-everything’ era.
On the other hand, web app development is also evolved to a great extent. Right from the static websites to dynamic to the single-web application, many concepts and technology have been introduced and used. Web developers are giving priority to responsive web design and exploring ideas like progressive web app and cross-platform applications.
While there is an app for almost anything, users are finding it difficult to install, maintain, and use various apps in one device.
The factors need to be taken into account are:
- The increased app size
- Not frequent use of the app
- Low connectivity of the internet
- High data and storage consumption
- Frequent updates and permissions
- Number of alternatives for a particular purpose such as food delivery, e-commerce, and so on
PWA is the just the right thing to overcome these problems. How?
PWA bridges the difference of web and mobile and provides users with superior and native-like performance in a web browser. In the simplest terms, it is a type of mobile app delivered through the web.
Sounds interesting? Here are some characteristics of Progressive Web Apps:
- It provides super-rich experience: Due to modern web standards, it offers an appealing user experience
- App-like experience: while using it, you will feel native-like experiences and functionalities
- Secure: It uses HTTPS to prevent any threat and vulnerability
- Modern: thanks to the functionality like service workers, these apps are up-to-date
- Greatly responsive: PWA works best for mobile, desktop, tablets in terms of responsiveness
- Works offline, on the low-quality network: This is most important; it runs offline and even in low-connectivity
- Linkable: It is usually shared via the link and does not need a separate installation.
Add to Home Screen Prompts: Key Attraction of PWA:
To facilitate installation, PWA provides “Add to Home Screen” popup which allows users to easily install the app on mobile devices. This feature is one of the significant reasons behind the popularity of the app. On the acceptance of the prompts, the app will be installed easily and quickly.
Let’s discuss, what happen in 3 steps:
- Add to Home Screen.
- Launch the web-app from Home Screen.
- Fullscreen “app-like” experience.
Pros of AMP’s
- Up to 4 time faster page loading
- They improve SEO and keyword ranking in mobile searches
- They support all ad formats and ad facility
- Extremely useful for content-based websites like new publishers
- Pages with a valid AMP version have a huge opportunity to outrank those who haven’t adopted this feature yet. AMP version pages have more chance to get their content visible on the front page.
Cons of AMP’s
- Lower user engagement compared to HTML pages
- Lazy load functionality for images
- They cannot track user activity on AMP pages
- They can’t enhance search engine rankings
- Not suitable for e-commerce website since it doesn’t include all the fancy elements required to boost user engagement.
Let’s also discuss about the Pros and Cons of PWA’s
Pros of PWA’s
- Fast page loading regardless of the network’s quality
- No installation or app updates needed
- Can be easily accessed through the home screen icon
- Allows smooth navigation and animations
- Can be used offline
- Maximized reach and a higher rate of engagement thanks to features like push notifications
- Relatively cheaper than native apps
- Unified customer experience
- Secure and less intrusive
Cons of PWA’s
- They do not support all native features
- Not all devices support the complete software functionality
- Call features without the Dialer dialog
- Modify logs or system settings
- Access to contacts, camera, calendar, alarm, browser, etc.
- Access to sensors and hardware features
- Not all hardware functionality supported
- Not all browsers supported
The Differences Between AMP and PWA
- Both AMP and PWA work to reduce the loading time of web pages on mobile devices. While AMP primarily reduces loading time, PWA pages update quickly to let the users experience a mobile app-like website without interruption.
- AMP focuses on providing content as fast as possible, while PWA focuses on delivering a rich user experience and engages users via push notifications etc.
- AMP is best suited for lightweight content like articles and blogs, while PWA is suitable for e-commerce sites.
Which is Better, AMP or PWA?
There is no clear winner between AMP and PWA as both perform best in combination. While one provides you instant content, the other ensures that users engage and interact with the website.
The choice between the two also depends on the type of website that you run. AMP sounds good for sites that aren’t too media heavy and mostly contain static content, for instance, news publications. But if you’re running an e-commerce site, you will let visitors have a user-friendly experience even without installing your mobile app. In such a case, PWA will be a wise choice.
Here is a list of impressive Progressive Web App examples across a variety of industries – so you can experience the new web technology yourself.
Does PWA’s Replace Android and iOS Apps?
We all know that today we spend 80% of our time on using a mobile phone, and most of the phones are either Android or iOS. But another fact is that a user isn’t opening the heavy apps developed for a particular application to run; rather, they are simple apps.
However, the cost of the development of apps in comparison to web applications is much higher. The PWA’s provide the advantage of running a cost-effective solution but shortly no way a replacement to the Android and iOS apps.
A good PWA is replacing mobile websites at a rigorous rate. But the charm of building new apps in native languages still allure the mobile developers. However, the mobile first approach @ web is a new technology that will improve the customer’s engagement on the web. Also, it will act as a great tool when it comes to developing and engaging and enriched web experience. The successful implementation of PWA’s has opened new opportunities for web developers. The PWA’S offline supports to run web applications is greater. It further leads to the development of other applications such as great eCommerce experience, push notifications, and saving the page load time.
Major requirements of a PWA are:
- HTTPS enabled website
- PNG icons etc
It should be noted that PWA is only supported with the HTTPS-secure website which means it won’t work with the websites that are still using the insecure HTTP protocol. If you’re website is not having the HTTPS support you can either install the SSL or join the biggest free content delivery network (CDN), Cloudflare that has inbuilt HTTPS (SSL) support and that’s of free of cost.
But, In this blog, I will also give you a working example of PWA.
So, Let’s code a PWA application.
Let’s create a simple webpage with some styling in it. The files are index.html & index.css.
Now, We would be following five steps towards adding and integrating the PWA and “add to home screen” option to our webpage.
Step 1 – Generating PNG icons
Generate the PNG images of our logo in the 64×64, 192×192, 256×256, and 512×512 pixel sizes. Tons of websites offer free generation of icons and favicons in different sizes. I’ve downloaded the images from flaticon, otherwise you can download the image from the git repository.
Step 2 – Creating manifest.json file
Every PWA requires a
manifest.json file. The web app manifest is a simple JSON file that tells the browser about your web application and how it should behave when installed on the user’s mobile device or desktop.
Create an empty file named
manifest.json in the root of our website and add the following code in it. A complete
manifest.json file for a progressive web app.
A typical manifest file includes information about the app name, icons it should be use, the start_url it should start at when launched, and more.
Tell the browser about your manifest
When you have created the manifest, add a
link tag to all the pages that encompass your web app:
<link rel="manifest" href="/manifest.json">
- short_name / name
You must provide at least the
name property. If both are provided,
short_name is used on the user’s home screen, launcher, or other places where space may be limited. name is used in the app install prompt.
When a user adds your site to their home screen, you can define a set of icons for the browser to use. These icons are used in places like home screen, splash screen, etc.
icons is an array of image objects. Each object should include the
sizes property, and the
type of image.
start_url tells the browser where your application should start when it is launched, and prevents the app from starting on whatever page the user was on when they added your app to their home screen.
start_url should direct the user straight into your app, rather than a product landing page. Think about what the user will want to do once they open your app, and place them there.
background_color property is used on the splash screen when the application is first launched.
You can customize what browser UI is shown when your app is launched. For example, you can hide the address bar and browser chrome. Or games may want to go completely full screen.
theme_color sets the color of the tool bar, and may be reflected in the app’s preview in task switchers.
If you want to read more about manifest file in PWA. click here.
Step 3 – Creating service-worker.js
service-worker.js is an important file that will handle various events and also it will show the “Add to home screen” pop up dialog, help in generating the web APK for your websites by fetching the details from your
So, to fully appreciate the true and awesome power of PWA you’re gonna to understand service worker because these dudes right here are the beating hearts of progressive web application. They allow us to do all of the different things that you would expect from a modern app that runs on a mobile device such as load content offline so you can still open and view the app without an internet connection by using cached assets and data. They also allow us to use background sync so that if a user tries to perform an action while the rough line that normally requires a internet connection for e.g. posting a status update, then it will perform the action in the background when a connection is re-established and that’s really awesome they’re also going to allow us to do things like push notifications so that our app can notify users on a device of something for e.x. a content reminder or new messages they might have on the app so these are the kinds of things that service workers allow us to do.
Now, when we create a service worker js file it doesn’t run on this same thread as our regular js file it runs on a different thread in another part of a browser isolated away from the HTML page now because of that this thread right here it does not have access to the DOM so it cannot directly read, change or remove page contents, our service workers have a different job to do. Service worker runs in the background when our application closes whether that be closing a browser tab or the whole application in a mobile device now their job is to handle the app like functionality by listening and reacting to events which occur in the browser such as push notifications made from a server to the browser or fetch Http request made by the browser.
What’s the point of a service worker if it can’t access the DOM? The reason is quite simple — service workers run in the background. Imagine uploading a large 30-minute video and while the video is uploading the browser completely freezes. Would that be a good user experience?
Of course not. That’s why we have background services for image video processing, listening real-time for data requests, push messages, etc.
Service Worker Life Cycle
Service Worker lifecycle has 3 steps: Registration, Installation, and Activation.
A service worker must be registered by a website because some browsers still don’t support service workers you should perform a feature check before registering a service worker. This is done by checking for the presence of serviceWorker in navigator(browser).
Service workers are still considered as “cutting edge” feature and not supported on all browser. Only Chrome, Firefox, and Opera have full support for service workers and their browser caching.
Where should we use registration function?
You can start registration process every page load if you need. Because this process doesn’t start from the beginning every time. If service worker is the new or updated, the installation process will start.
To register the service worker, call ‘navigator.serviceWorker.regsiter ‘. Pass the path to the service worker. The register function returns a “promise” because it is an asynchronous function it give response in then(). You can use the response if you like, we just simply console log that “SW is registered”.
If successful, the promise returns a reference to the service worker registration object. From there you can perform specific UI tasks as needed.
Make sure that you have to run this app using live server, because to run PWA you need a HTTPS enabled website. So, In our case, we will be using Live Server Extension.
You can get this Extension in the VS Code. To run the app just right click and select “Open with Live Server”.
This will open the app in the new chrome window.
By using Live Server, our app is run on a server but it’s not HTTPS protocol enabled it’s a HTTP. Now, you will question that you have to said that PWA requires HTTPS but in this case it is HTTP. Yes, you are right, because we are working on localhost which is acceptable according to PWA.
Let’s view Manifest file in DevTools.
Whatever, we have declared in the manifest.json file is there in this Manifest such as name, short_name, icons.
If you want to check is your service worker is registered or not open the developer tool after run the app. In the dev tool, open the Application -> Service Worker tab, you should see the service worker running.
To make sure it’s the current service worker and not a cached one, click on the Sources tab.
Yup, it’s the one.
Installation (Install Event)
Install is the event that gets the party started. On this step, the service starts the caching and if content is cached successfully the service worker becomes installed. In my activate event, I am caching the files in my filesToCache array. If this step fails the service will not proceed to activate.
We have to write the installation code in the sw.js file.
Let’s try to understand the code of an installation process. Firstly, create a variable for our cache name I’ve named the variable as “fileToCache” with a value of ‘pwa-cache‘. Now, To add our assets(files) to cache we need to create an array and you know the format of array (comma separated values). First we will give the path of root & index.html with all the files and also images.
Notice the self keyword. Remember, we don’t have access to the DOM window object, so we use the self key to reference to the currently installed service worker.
We write self.addEventListener – we will listen for the ‘install’ event here, we call a function for this event. We target the install event and write evt.waitUntil, it means event will wait until the work inside written is not completed. What will we do inside? We will cache files inside this. The code is caches.open(), it will create a new cache with the name we pass inside it. We will give the ‘fileToCache’ reference. It’s also an async function, (all cache function/method are async). After creation, it will give us that cache in .then() method – we will go to that cache and return cache.addAll() it will add all the referenced files in that cache. If we look for any error, using .catch() – we will console the error (‘error adding files to cache’). After all this happened, I’m gonna console here that ‘SW installed‘.
The service worker has installed. Now, Let’s have a look to our cache files.
To view the cached files, Go to Application -> Cache Storage.
Now, If go offline we will still see that dinosaur(no internet page) instead of files, because they are cached but we are not managing them yet.
So, now we will work in the activate event.
Activation (Activate Event)
This is the event that triggered when the “install” event is completed. If the current page is out of scope, this isn’t triggered.
This event is the ideal location for removing cached static content if it has a newer version.
Another important point, If you refresh current page when sw.js is updated, you can’t access new one. You must close all existing window/tab and start again for updating. If you want to manage this process from code behind, you can use “self.skipWaiting()” function in sw.js file, the “install” event is ideal location for that.
You can track and manage page network traffic with this event.
Let’s view the cache response.
If we refresh our page in offline mode, it works because our files are cached and working offline.
I want to bring you back to the overall goal that we’ve got here we are trying to make a PWA and service worker are just one part of a PWA and it’s very important but they are just one part like a web app manifest file is another part of PWA. So, a PWA is made up of several different things and we need to implement them all together to make our PWA valid. Now, chrome dev Tools give us a a way to audit our app using the lighthouse plugin which essentially gives us a checklist of required actions to our site invalid PWA.
So, Let’s have a look at this in action just audit what we’ve got so for so I’m going to go over audits in the top tab then make sure that you have PWA (Progressive Web App) checked. I’ve have unchecked the rest but you can keep those checked if you want them come to the bottom and click “Run audits” and is just going to take a few seconds but then it will spin up a report for us with some different things in the checklist that you need to complete.
It’s split up into 3 different sections (Fast and reliable, Installable, PWA Optimized). Now, the one’s in green over here with a dot they are passed and the one’s in read they are not passed.
But, In our case, One checklist is failed which is “Does not redirect HTTP traffic to HTTPS“. That’s completely true and will be fine because we are working on localhost. Which is an exception in PWA so no worry for now.
Now, the another checklist I want to show you is for the “Add to home screen” banner. When we were on android device or something like that we go to add to home screen in the browser menu but there was an easier way to prompt the user to add our app to the home screen and that’s the install banner. Now, the install banner in chrome can automatically appears and it’s based on certain criteria so it only appear if all of this criteria are met.
In order for a user to be able to install your Progressive Web App, it needs to meet the following criteria:
- The web app is not already installed, if installed then delete it.
- Meets a user engagement heuristic (previously, the user had to interact with the domain for at least 30 seconds, this is not a requirement anymore)
- Includes a web app manifest file which contains: short_name, name, icons, start_url and display properties.
- Served over HTTPS (required for service workers)
- Has registered a service worker with a
In our case, we have met all the above criteria. Now, Google on Android devices will automatically show a banner prompting the user to add the app to the home screen and that’s we’re trying to do here.
The install Banner
Now, I want to test our app on the Real Android phone to see if we get this installed banner. Our web address is 127.0.0.1 then port 5501 remember that we had to do to show what’s on the localhost on our computer. Now, remember service worker only work over HTTPS connections and localhost is the exception, but when not on localhost here is showing us what some localhost on our development computer. But we’re not on localhost up here so this is actually not going to work so what we need to do is find out a way to able to type in localhost port 5501 here and see the website because localhost was the exception to the rule where we don’t have to use HTTPS and the service worker will still work it won’t work using this so how we do that well we’re going to use a bit of Port forwarding by using the chrome dev tools.
To open that in dev tools, Go to More tools -> Remote devices what we’re gonna do now is connect up this remote device with chrome tools.
We can see already the device is detected by chrome dev tool. Now, what we’re going to do is go back to settings and we’re going to check Port forwarding and we’re also add a rule now the port that we want to visit on here using localhost it’s gonna be 5501 . Which is just localhost port 5501 now that’s the same as 127.0.0.1 port 5501 these two things are the same localhost.
I want you to forward this address on our device over here to this address on our development machine. To check the app in your mobile you have to visit localhost:5501. It will open the app in your mobile browser.
Now, we can see this install banner at the bottom of the screen because we have satisfy all those conditions. So this is much nicer way than having to go to the three little dots up here the settings and then adding it to the home screen not everyone knows how to do that but now the user is being prompted to add app to their home screen via a little banner that google chrome is automatically popping up for us.
For Demo, Watch the below video.
BOOM!! We have created a simple PWA app.
You can find the source code from here.
Hope you will enjoy reading this blog. 😊
Thankyou & peace. ✌