How to Build a React Progressive Web Application (PWA)

January 17, 2019 0 Comments

How to Build a React Progressive Web Application (PWA)

 

 

If you aren’t talking about PWAs you are seriously missing out. PWAs in recent years has grown to be the most adopted optimization trick in the software industry.

Not only optimization benefits but a plethora lot of goodies:

  • Progressive enhancement: It works for every user no matter the browser choice of the user. Your app will run properly on a wide range of browsers and will degrade gracefully when certain functionalities are not available but still with a decent user experience.
  • Native-like experience: It provides a mobile-like experience. It is a web app but it feels like you are interacting with an Android/iOS app.
  • Responsiveness: It can match to fit any screen size be it a tablet, mobile, iPad or desktop. It automatically adjusts to compensate for either a new space or a narrow space.
  • Offline support: Your app can work offline.
  • Push Notifications: PWAs are engaging with the use of push notifications, they pop up a notification to notify about either a friend request, current news, new message or any other thing, you will feel the urge to respond to the notification(to respond to the message, to read the news, to check out the new friend) and launch the app again, thereby re-engaging you with the web app.

Service Workers is a type of Worker that lets us run scripts in the background of our browser. It is like a man-in-the-middle between our browser and the network. The main work of Service workers is to help us cache and serve the cached files which provide an uninterrupted user experience.

Service workers allow developers to manage resource caching more efficiently so that users don’t experience interruptions even if they disconnect from the internet. — KeyCDN in What Are Service Workers and How They Help Improve Performance

In normal web apps, we can only navigate through our website if we are connected to a network, without the network we will see the usual “Network error: Page cannot load” or Chrome little dinosaur game. But service workers have changed the game, with service workers we can cache our website pages not only web pages but other resources that do make up our web pages apart from the text. Service workers cache webpage resources in a new storage called CacheStorage, when we go offline the service workers kick in and serve the cached pages in the CacheStorage.

We understood how service workers workes in the above section. Now the question is: What is the Progressiveness in the PWA acronym?

Progressive Web App (PWA) is a term used to denote a new software development methodology. Unlike traditional applications, progressive web apps are a hybrid of regular web pages (or websites) and a mobile application. This new application model attempts to combine features offered by most modern browsers with the benefits of mobile experience. — Wikipedia

Most of the PWA features are not yet supported in most browsers and more features will be added in the future. You don’t have to implement all the features. If your browser doesn’t support app manifest but support CacheStorage, you can leave out the app manifest and start with the CacheStorage, if in the future your browser(on update) come to support app manifest you can then add that feature to your PWA.

You see, you keep progressing as more features are added to your browser without a total halt and waiting for your browser to fully support all the PWA features.

In this post, we will learn how to build a PWA in React.

Note: When building a React web app, it’s very recommended to use Bit. It lets you easily share, organize and reuse your components so you and your friends can use and sync them across your apps and projects- to build faster.

We can create our own SPA app using React. We will scaffold our React using create-react-app. If you don't have it installed globally in your system, run this command:

npm i create-react-app -g

Next, we create a React app.

create-react-app react-pwa

The following files are created in your react-app folder.

The manifest.json in public folder holds the information(metadata) that controls how your app appears to the user and define its appearance at launch.

shortname: This specifies the name your app will take when added to your Home screen.

name: This is the name Chrome used to prompt the Add to Home screen. The prompt goes like this “Add yourappname to Home Screen", here the yourappname is replaced by the value of the name property in your manifest.json. If name is not present shortname will be used.

icons This specifies the icon displayed along with your app name in your Home screen.

starturl: The URL where your app starts so it doesn’t start from a random page or where you left off.

display: Here you can customize the browser view. You can hide the address bar and the Chrome browser to make the app look native, make the app go fullscreen, run on its own window.

themecolor: The color of the browser toolbar

backgroundcolor: The color of the splash screen that shows when the app is launched by clicking on its icon in the Home screen.

The manifest.json in linked in our public/index.html file:

<link rel="manifest" href="%PUBLICURL%/manifest.json" />

Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the public folder during the build. Only files inside the public folder can be referenced from the HTML.

Having a manifest.json is required by Chrome to add your PWA to Home screen.

The serviceWorker.js registers our service worker file. You may ask where is the worker file it will be registering? The file will be generated by create-react-app when the app is built, ie when are building for production:

npm run build

The command builds our project and stores it in the build folder.

The static folder holds all the js and css files. The index.html is our main page that loads all our React files stored in the static/js folder and also our CSS that is stored in the static/css folder. We can the service-worker.js file, that’s where all service worker code is stored. The precache-manifest..js file holds all the files the service worker caches in an array. We see the manifest.json file, as we already know it tells the browser how our PWA will behave.

To see everything play out, we will load the build folder in our browser but first, we need a browser. Install the http-server

npm i http-server -D

Next, add start to the scripts section of package.json:

"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"start-sw": "http-server ./build"
},

Here, we are telling the http-server to serve the files in the build folder.

Now run npm run start-sw in your terminal. Navigate to 12.0.0.1:8080 in your Chrome browser.

How do we check if the app is a PWA? Simple, we check in the Devtools tab.

Open your Devtools and click on Application.

On the right tab click on Service Workers

Oops!!! Nothing is there, so therefore our app is not recognized as a PWA. But why? we had service-worker.js and prefetch..js files generated.

The answer lies in our index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();

See the serviceWorker is not registered. To make our app a PWA we need to change the unregister() call to register()

// ...
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.register();

We will rebuild our project. Run the command:

npm run build && npm run start-sw

Now, reload your browser. You will see service-worker.js appear in your Devtools > Application > Service Worker tab:

To see which files have been cached, move to the CacheStorage tab and click on it:

you see it cached the index.html file, which is our main page, the CSS/JS files, and the React logo. It didn’t cache the manifest.json or asset-manifest.json because our page doesn’t it to display its contents.

To test whether our app will work when offline. We can simply shut down the server by doing Ctrl + C and running the server again when we want to go online again. You'll found out that we will regularly shut down and start often times.

We can save our selves the stress by simply making the browser itself go offline, ie making simulate offline mode so our server will keep running. To do that, go to Application > Service Worker and click on the offline checkbox:

A yellow triangle icon will show on the Network tab. If we go to the Network tab, you will see that the offline checkbox is also checked:

Our browser is now in offline mode. If we reload our browser you will see our page will load without “ error fetching page”, but before we do that make sure you disable your browser cache so we know the browser isn’t serving the page from its cache. You can do that by clicking on the disable cache checkbox in the Network tab.

In this post, we looked at PWA and made a list of goodies it provides to modern day web development and performance in a nutshell.

Next, we saw how we could build a React app using the create-react-app utility and took us to the DevTools to see where the how our Service Worker file run.

Here we only showed how to set up a basic React app and how to use the Devtools to your advantage. In the next post in the series, we will build on this to show how Service worker really impacts on a real web app. Till then.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment and ask anything below. Thanks !!! 👏


Tag cloud