Category Archives: Web Development

Better Development Experience with Vite

Few days back I came to know about an amazing frontend tool Vite. Since then I am exploring it a bit. Here in this blog post we will go through some of the feature of Vite. We will also see how Vite can make your web development experience faster and better.

Vite – Next generation frontend tooling

There is already a discussion going on around Vite as a replacement of Webpack. In this post we will avoid this discussion. We will focus more on features of it.

What’s the need of bundling tools like Vite in your web app?

Since the ES6 modules introduced it’s a good practice to write JS code in a modular fashion. But in early days a lot of browsers were not handling loading ES6 modules natively. So we have the concept of bundling our code, using tools like webpack. The tools like Webpack and Vite converts source modules into the code that can run in the browser. These tools crawls through your code, find out dependencies and process it. Once processed it generates the bundle of all your module which can run in browser.

What are the problems with existing tools?

As we mentioned above the tools like Webpack and all, crawls through source code and process it. This works fine when you have smaller project and less no of modules. Once project grows and no of modules grows, we start experience following issues.

  • Very Slow start of dev server
  • Slow file updates
  • Slow HMR
  • Longer build time

The reason is, code transpile and concatenate takes time once your project grows. This affects the developer ‘s productivity. Every time we have to wait for the build and to start the dev server for every small changes.
So how Vite solves these issues? There are two primary things.

Pre bundling of Dependencies

When we work with web apps we use lots of vendor packages. These are external dependencies which are not going to change during the development. What Vite does is, it pre bundles these dependencies esbuild. esbuild is extremely fast JavaScript bundler.

Dependency resolving and serve

For the application source code, it resolves the dependencies and only transform and serve source code on demand. That means no time spent on bundling your source code before server starts. Here browser will take care of bundling and requesting the module as and when it’s required.

This leads to a great developer experience as we don’t have to have for serve to start. Also there is blazing fast HMR.

Here is how Vite works.

Vite work
How Vite works?

Getting Started with Vite in your React Project

Let’s see an example of how to work with Vite in your React Application. First we will start by adding necessary dependencies in your app.

"devDependencies": {
    "@vitejs/plugin-react": "^1.0.7",
    "vite": "^2.7.2"
  }

Also you have to add a config file. Following is the bare minimum configuration needed. For more options you can check out the documentation here. Vite config

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()]
})

To start the dev server with Vite, you just have to use command vite or npm run dev. Once this command is executed it will look for index.html file where you should specify your entry point.

<script type="module" src="/src/main.jsx"></script>

That’s it and it will start the dev server in fraction of seconds. If you check the network tab of your browser you can see the main.jsx is loaded as native ES module.

Vite ES native module
Vite ES native module

Fast HMR

HMR is the strategy to allow module to Hot Replace it self without affecting the page. This way we can see our changes instantly on the screen. This works fine when have smaller code but as your project grows HMR takes lots of time. This greatly affects the productivity as every time we have to wait for bundling.

When file is edited and saved it just invalidate the edited module and and its closest HMR boundary. Also if you see network tab, Vite requests the source cod with specific HTTP headers. For dependencies module requests, it uses the cache control header to cache the requests so it does not hit server. For source code module requests it uses 304 Not Modified to conditionally load it.

Because of all these features Vite is becoming popular among developers and its adoption is increasing day by day.

I will soon share my experience of replacing Webpack with Vite in larger project.

React Developer Tools for Better Development

In this blog post we will go through some of the useful React Developer Tools, that can help you in development and debugging of your React apps. Using this tool one can write better and cleaner code.

React

React Developer Tools

Some of the tools which we are going to cover here are Debugging Tools, Libraries, Test utilities etc. Using these tools you can enhance code quality and performance of your react app.

React Developer Tools I have mentioned here are based on my experience with it and use in the projects I am working on. If you know any other React Developer Tools, feel free to mention about it in comments.

React Developer Tool

This tool is available as browser extension for major browsers like Chrome, Firefox, Edge. It is also available as separate NPM package if you want to use it in mobile browser for debugging. Here is the link react-devtools

This is very popular tool, useful for both developing and debugging React apps by all the developers worldwide. Also known as React dev tool gives you a way to debug the rendered components through tab in dev tools. You can view all the props and its value for a particular component.

The feature, I like most is the, visual representation of components re render with timestamps. This is most useful for enhancing the performance of the React App.

Storybook

This is a tool for developing your React UI components separately. It helps in terms of development, testing and documentation of UI components. Imagine that you want to showcase some UI component before using it in project. Using Storybook this is possible.

As a developer, we can create develop the component and share with teams to play with it. It works outside your react project so you don’t need to make any changes in project. You can simply create components and share the storybook with your teams. Checkout official Github of Storybook

Why Did You Render

While React Developer Tool can show the visualisation of re renders, WDYR can notify you about potentially avoidable re-renders. In short it can show you the possible root cause and then you can debug more and fix it. It also works with React Native as well.

This is a nice tool for performance tweaking of your React apps. It is available as NPM package, you can install and use it in your React app. For documentation please check the official Github page of WDYR

Webpack Bundle Analyzer

This is very useful tool to for analysing the application bundle to find out which modules are heavy and which modules can be removed. It uses the webpack stats JSON file to provide us with an interactive treemap visualization of the contents of our bundle.

It is available as npm plugin so you can install and configure it to use in your React application. Checkout the official GitHub of Bundle Analyzer

JEST

Jest was created by Facebook and is a testing framework to test javascript and React apps. You can do unit testing with JEST for your React App. Unit testing is utmost important to reduce bugs in your production app.

JEST is pretty much simple to configure and use with your React App. You can add it as npm package and set up the test. Writing unit test cases are considered to be good practices for the development. You can refer to official GitHub of JEST

Frontend Development trends to Look For in 2022

As we are moving to new year 2022, it’s good to keep an eye on Frontend Development trends. You should keep up with this latest trends so you don’t miss any opportunity that could be a turning point of your career.

In this blog I am going to mention some Frontend Development trends, you should not miss out. This is based on what I have learned from industry. If you have some different opinion, feel free to share your feedback in comments.

1) Progressive Web Apps

Progressive Web Applications
Progressive Web Applications

PWA is already trending since last few years thanks to its native app like capabilities. It can be installed like native app. You can work with it offline. It is blazing fast. Major mobile browsers now support it. With PWA, you can access hardwares like camera, microphone etc.

Above all capabilities, made PWA favourite among developers and businesses operating over internet. Lots of businesses are using it and many more are vouching for it in upcoming year. Hence if you are a PWA developer you may have great chances to work with major online businesses.

2) Micro Frontend Architecture

Micro Fronend Architecture

In a simple words, it’s about breaking monolith frontend to smaller and independent applications. Together it works as one single application. This gives you more control over development and CI /CD. Many teams can work together and combining it together makes your entire frontend.

Many companies have already adopted this architecture and their productivity has been increased. This trend is going to dominate in upcoming year. If you are front end developer or architect it will be good to learn about this.

3) Rise of Voice User Interface (VUI)

Voice User Interface (VUI)
Voice User Interface (VUI)

Accessibility is a prime thing to look for in web application now a days. This gives rise to Voice User Interface. As a human, voice / language is the most natural way of communication for us. This is also another major reason behind the rise of VUI. Major companies like Amazon, Google, Apple has introduced the platforms like Alexa, Assistant and Siri. These platforms are open for developers to build applications on top of that.

Power of text to speech and speech to text technologies has increased exponentially. These gives good accessibility to your web apps. Your users can interact with apps with voice and also it is blessing for visually impaired people. There are still major challenges in this area. Like understanding regional languages. But it’s worth adding VUI in web app.

4) Rise of JAMstack

JAMstack ==> JavaScript + API + Markup

JAMstack

Core principles of JAMstack are Pre rendering and decoupling. JAMstack makes web app faster, more secure and easily scalable. You can convert your entire frontend to highly optimised prebuilt static pages which can be delivered from CDN. Let’s understand each part of JAMstack

JavaScript

As we know JavaScript is most popular when it comes to building web application. Using the modern frameworks like ReactJS, Angular, Vue and Svelte, we can develop web apps which is modularised and easy to maintain.

API

API plays vital role in JAMstack. As a developer it’s up to you that how you can make your JAMstack app dynamic by utilizing the API in proper way. From JavaScript you can make API call to multiple host which will deliver the content.

Markup

This is the most critical part of JAMstack. To be considered a JAMstack app, your app should server the HTML statically, which means not being dynamically rendered from a server. Markups is your prebuilt and pre rendered content. It is requested by JavaScript through API. Frontend developers can use frameworks like Gatsby, NextJs for this.

5) Rise of GraphQL

GraphQL

Facebook introduced GraphQL in 2018 to address the issues with REST APIs. The issue with REST APIs are you have make multiple network requests to get the entire data. This leads to performance degrade both on front end and back end. Using GraphQL we can obtain entire data with one single quest from one end point.

Few advantages of GrapQL is, it’s much faster, strongly typed and follows hierarchical structure where relationships between objects are defined in a graphical structure. Many big companies are using GraphQL. As a front end developer it’s good learn about GraphQL as more and more businesses are moving towards GraphQL

6) Web Assembly

Web Assembly

Most of the time we use JavaScript for the web development. With web assembly developer can use code written in C and C++ in web browser. WebAssembly can help client apps to run on the web that previously was not possible. Sometimes we need to build app in lower level code like C, C++ etc. For example games or streaming apps. But it can’t run on web but with Web Assembly we can write apps in C, C++, RUST, Go Lang and run on the web with near-native performance. Web assembly works along with JavaScript in browser.

7) Machine Learning / Augmented Reality / Virtual Reality

How you can leverage the power of ML, AR & VR in your web app. To know more about this check out my session on Google DevFest India 2021 Day3

Hope you liked this blog about Frontend Development trends and keep exploring it more.

DialogFlow API – Use in Laravel

DialogFlow is one of the best tool available for Machine Learning. It is developed and maintained by Google Team. You can use DialogFlow for various applications like Chat bot, Customer support service etc. In this blog I am going to explain how you can connect DialogFlow with Laravel using APIs.

DialogFlow Logo

DialogFlow

Generate Connection File

For using API, you first have to generate connection file which will be used for Authentication. For this here are the steps.

  1. Login to DialogFlow Console
  2. Select the Project
  3. Go to Settings
  4. Click on Service Account Link
  5. You will be redirect to Google Project Console.
  6. Select Service Account menu from left hand side.
  7. Click on Add New Service Account
  8. Follow the steps and add last step create and download JSON file.

This file will be used as connection credentials.

Integrate SDK in the Laravel App

First of all you have to download SDK using composer. Execute command in terminal

composer require google/cloud-dialogflow

This will download the SDK in vendor folder. Now set a link of credential file in ENV file.

GOOGLE_APPLICATION_CREDENTIALS= /path/to/your/file

Now you can use the API to connect to DialogFlow. Here are few examples.

First of all add following dependencies in your file to use the SDK.

use Google\Cloud\Dialogflow\V2\IntentsClient;
use Google\Cloud\Dialogflow\V2\Intent;
use Google\Cloud\Dialogflow\V2\Intent\TrainingPhrase\Part;
use Google\Cloud\Dialogflow\V2\Intent\TrainingPhrase;
use Google\Cloud\Dialogflow\V2\Intent\Message;
use Google\Cloud\Dialogflow\V2\Intent\Message\Text;

Get List of All Intents

Now use following code to get list of all the intents.

$intentsClient = new IntentsClient();
$parent = $intentsClient->projectAgentName(“YOUR DIALOGFLOW PROJECT NAME”);
$intents = $intentsClient->listIntents($parent,array(“intentView”=>1));
$allIntents = array();
$iterator = $intents->getPage()->getResponseObject()->getIntents()->getIterator();
while($iterator->valid()){
$intent = $iterator->current();
$allIntents[] = array(“id”=>$intent->getName(),”name”=>$intent->getDisplayName());
$iterator->next();
}
return Response::json(array(‘success’=>true,”allIntents”=>$allIntents));

Get Text Prediction

Use following code to get text prediction.

$sessionsClient = new SessionsClient($credentials);
$session = $sessionsClient->sessionName($projectName, uniqid());
$languageCode = ‘en’;
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);

// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);

// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();

Progressive Web App – Add Web Push Notification

Welcome to Progressive Web App Series. If you have missed previous blog posts, please read from following links. In this blog post we will understand how to add Web Push Notification in PWA.

  1. What Are Progressive Web Apps?
  2. App shell – Progressive Web App
  3. App Manifest – Progressive Web App
  4. Progressive Web App – Service Worker

Why We Need Web Push Notification?

The best way to engage end users is through push notifications. User visits your PWA but then he didn’t come back. You can still reach to user by way of notifications. This will engage your end user. Notifications could be for multiple things. For example.

  • New content in PWA
  • Real time alerts
  • Daily trips and tricks
  • Updates like order update, invoice update etc.

PWA supports Web Push Notification just like native mobile apps. In this post we will explain how to add web push notification using Firebase.

Create Firebase Project

To create firebase project go to Firebase Console and login with your Google account. After you create project go to your project settings and get the sender id and add to your manifest file. Check the screen shot.

Web Push Notification Sender Id

Web Push Notification Sender Id

gcm_sender_id : “YOUR_SENDER_ID”

So now we have sender id. Next step is to register for push notification.

Register for Push Notification

After your service worker is registered, you can register for push notification.

 

if (‘serviceWorker’ in navigator) {
navigator.serviceWorker
.register(‘service-worker.js’)
.then(registerForPushNotification);
}

function registerForPushNotification(){
navigator.serviceWorker.ready.then(function(registration) {
if (!registration.pushManager) {
alert(‘Your browser doesn\’t support push notification.’);
return false;
}

//To subscribe `push notification` from push manager
registration.pushManager.subscribe({
userVisibleOnly: true //Always show notification when received
})
.then(function (subscription) {
console.log(subscription);
var rawKey = subscription.getKey ? subscription.getKey(‘p256dh’) : ”;
var key = rawKey ? Base64EncodeUrl(btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey)))) : ”;
var rawAuthSecret = subscription.getKey ? subscription.getKey(‘auth’) : ”;
var authSecret = rawAuthSecret ? Base64EncodeUrl(btoa(String.fromCharCode.apply(null, new      Uint8Array(rawAuthSecret)))) : ”;
console.log(“Key: ” + key);
console.log(“AuthSecret: ” + authSecret);
console.log(‘endpoint:’, subscription.endpoint);
//Save Data on Server.
})
.catch(function (error) {
alert(‘Oops, you have disabled push notificaitons. I will not be able to give       you real time updates.’)
});
});
}

function Base64EncodeUrl(str){
return str.replace(/\+/g, ‘-‘).replace(/\//g, ‘_’).replace(/\=+$/, ”);
}

function Base64DecodeUrl(str){
str = (str + ‘===’).slice(0, str.length + (str.length % 4));
return str.replace(/-/g, ‘+’).replace(/_/g, ‘/’);
}

Above functions will subscribe user for push notifications. Key, AuthSecret and endPoint, you have to save on server so that later you can use it for sending push notifications from server to your PWA application.

Also before subscribe, you can also check if user is already subscribed for notification.

registration.pushManager.getSubscription()

If user is already subscribed then you will get subscription object and just update it on server.

Here in this blog I have mentioned how to send push notification using NodeJS script.

Send Firebase Push Notification with NodeJs

Once you get notification, you have to add listener to check for notification and show it to user.

For that you have to add event listener in your service worker.

self.addEventListener(‘push’, function(event) {console.log(event);
var data = event.data.json();

var title = data.title;

var body ={
‘body’: data.message,
‘tag’: ‘PUSH’,
‘icon’: ‘images/icons/icon-32×32.png’
};

event.waitUntil(
self.registration.showNotification(title, body)
);
});

Above code will show notification in default window.

Progressive Web App – Service Worker

Welcome to Progressive Web App Series. If you have missed previous blog posts, please read from following links. In this blog post we will understand one of the important component of PWA, which is Service Worker, which is nothing JavaScript file that take cares of caching, showing push notifications in PWA

  1. What Are Progressive Web Apps?
  2. Progressive Web App – App Shell
  3. Progressive Web App – App Manifest

What is Service Worker?

Service Worker

Service Worker

I am sure most of the developers are aware of concept threading. A thread is a process that can run in background without affecting the main process. Service worker is just like a thread for your PWA. It runs separately and independently from main browser thread. That means it runs in background and will be alive in browser in case you have closed your web application.

In your PWA application, a service worker is a simple JavaScript file where we can first register it, install it and activate it. Once it’s activated it will stay there till we remove it.

A Network Proxy

It can work as network proxy as well. It can intercept network requests and if needed it will block it and give you data from cache or it can let the request proceed and get you fresh data.This also gives offline capability to application. In case there is no network, we can intercept request and load data from cache. It is mainly used for showing web push notifications in PWA as it runs in background so it can subscribe for push notification events and we can easily handle push notification with it. Caching resources will make content load faster under most network conditions.

Restrictions of Service Worker

Since it runs in background, it does not have access to localStorage. It also can not access DOM, to communicate with DOM it post the messages. It can only work on HTTPS.

How to register it in PWA?

You have to create a service-worker.js file and first of all register it in your app file.

navigator.serviceWorker
.register(‘./service-worker.js’)
.then(function(){

console.log(‘Service worker registered’);

})
.catch(function(error) {

console.log(‘Service worker registration failed, error:’, error);

});

Scope of it will be defined based on where you put the file in your web app. If you put it in root folder, it can control all the files and can intercept network requests from all the file.

Installation of Service Worker

Once it’s registered and it browser treat it as new service worker, it will try to install it, you can also listen for the install event by adding install event listener in your service worker.

self.addEventListener(‘install’, function(e) {
console.log(‘[ServiceWorker] Install’);
});

Activation

Once service worker is installed, it will be activated and now it is ready to intercept network requests and caching. We can also add event handler for it.

self.addEventListener(‘activate’, function(e) {

console.log(‘[ServiceWorker] Activate’);

});

You can learn more about it on Google Developer Website.

Introduction to ServiceWorker

 

Progressive Web App – App Manifest

Welcome to Progressive Web App Series. If you have missed previous blog posts, please read from following links. In this blog post we will understand one of the important component of PWA, which is App Manifest, which is nothing but meta data about app.

  1. What Are Progressive Web Apps?
  2. Progressive Web App – App Shell

What is App Manifest?

The manifest allows developer to configure look and feel of PWA. For example if user saves it on home page, the icon will be displayed, that we can configure it in manifest. If you don’t add this file to PWA, user will not be able to save it on home page.

So you can configure app name, app icon, launch url etc. in this file. So user can distinguish it from other sites and apps. It’s JSON based file and following is the default structure of the file.

App Manifest

 

{
“name”: “PWA Demo”,
“short_name”: “PWA Demo”,
“icons”: [{
“src”: “images/pwaDemo.png”,
“sizes”: “192×192”,
“type”: “image/png”
}],
“start_url”: “/index.html”,
“display”: “standalone”,
“background_color”: “#3E4EB8”,
“theme_color”: “#2F3BA2″
}

After you create this file in your PWA, you have to link this to your html page. So browser will know about it and will use it’s metadata when users saves it on home page. Add following line to your head tag.

<link rel=”manifest” href=”/manifest.json”>

As you can see the structure of the manifest file, you can add title, short title and add number of icons. You can add different size of the icons for different mobile screens. For example for low resolution, you can add small icon.

{
“src”: “images/pwaDemo128.png”,
“type”: “image/png”,
“sizes”: “128×128”
}

Auto Generated Splash Screen

If you add above file in PWA and save it on home screen and open it, you will notice a splash screen coming up. That’s the magic of PWA. This splash screen is built with following things of manifest.

  • background_color
  • icon
  • name
  • theme_color

This splash screen will be displayed till its loading cached resources and other resources required to start the app.

The display property define the look and feel of app. If you set it as standalone, your app will be displayed in full screen and it you want top url bar to be displayed, you can set it as browser.

So by using this file, you can configure look and feel of your PWA app. In next post we will understand about service worker. You can also get more information about manifest from Google developers site.

Web Application Manifest

Send Firebase Web Push Notification with NodeJs

NodeJs

Sending Web Push Notification using NodeJs

Recently I was exploring NodeJs for learning and I had bit tough time in figuring out how to send Firebase PushNotifications with NodeJs. In this blog, I am going explain how to do this.

What is Web Push Notification?

Web push notifications are clickable rich content messages sent to your device by a website or a web app. Push notifications are delivered to your mobile device or desktop, even when your browser is closed. These notifications can only be sent to users who have subscribed for these notifications from a specific website. As these notifications are pushed to user’s device, users don’t have to be present on the specific website to receive these notifications.

Push Notifications are best used for delivering content in a timely manner and engage users. Other common use cases include retargeting, activation and retention.

For this blog we assume that you have added Firebase registration process on server side and getting following three fields from your client app.

1) Auth Key

2) p256dh

3) Endpoint

You will get this three things when you register for web push notification with Firebase. You have to save this on server for sending push notifications.

First of all for sending web push notifications you will need to install npm module web-push

If you have not installed it yet. Please install it first.

npm install web-push –save

Now that you have it installed, use following code to send Web Push Notifications.
const webpush = require(‘web-push’);
const sub = {
            “keys” : {
                “auth” : “AUTH_KEY”,
                “p256dh” : “P256DH”
            },
            “endpoint” : “END_POINT”
    };
const params = {
        title: ‘Test title’,
        message: ‘Hi How are you doing?’
    };
webpush.setGCMAPIKey(‘YOUR_API_KEY);
webpush.sendNotification(sub, new Buffer(JSON.stringify(params), ‘utf8’))
         .then(
             function (data) {
                 console.log(“sucesss”);
             },
             function (err) {
                console.log(err);
             }
         )
         .catch(function (ex) {
             //return callback(new Error(ex), null);
         }
    );
That’s it and now you will be able to send PUSH notifications using NodeJs
Hope this helps you.

Ngrok – Demo Web and Mobile Apps Without Deploying Them

How to show demo?

Before we know what is ngrok lets understand the problem first. As web application developer, we always face issue in demo. Most of the time developer works on local machine. But how to give demo to remote client. For that either we have to do screen sharing on Skype or team viewer.

Skype                TeamViewer

But its not always good experience. Sometime if connectivity is not good, screen will be blurred. Remote user will not have good and real experience. Other option is to deploy on web server but it’s not always feasible for web developers. Most of the time developers don’t have the remote server so how to do it?

Here comes ngrok, the secure tunnels to localhost You can check product here on their website. Click here

What is ngrok?

ngrok creates an secure tunnel to your local host and make it accessible to outside world.

Let me give you one simple example. For example if your local server is running it should be on http://127.0.0.1 and if it’s running on default port it’s port 80 or it could be your own custom port.

Now if you have installed ngrok, you can start deamon on particular port and it will give you one URL which you can give it to remote user. When they run it in browser, they will see your local web server. So when they run it request goes to ngrokcloud and it will forward it to your localhost server.

ngrok demo

(Pic courtesy : product website)

Quick Demo

Lets see things in action quickly. For example I have a web application running in my local MAMP server.

Local Server

Now I want to show it to my remote client. For that I have installed ngrok and started it’s deamon to point to 8888 port.  For this download and install it from ngrok website. Now run command in terminal

ngrok http 8888

It will start ngrok tunnel and will give you URL. In your case if you are using server without custom port then port no will be 80 or use your own port.

ngrok

As you can see in above picture it gave you URL which you can share to remote users for demo and when they run it in browser they will see your local website. Check the URL in below screenshot.

ngrok demo

That’s how it’s easy to show demo without deploying your web app or mobile app to server.

Progressive Web App – App Shell

Welcome to Progressive Web App Series. If you have missed previous blog posts, please read from following links. In this blog post we will understand one of the important component of PWA, which is App Shell, sometimes referred as Application Shell as well.

  1. What Are Progressive Web Apps?

The App Shell Model in Progressive Web App

One of the key feature of PWA is that it loads faster and that is because of Application Shell.  In native application we have all the content and resources are stored locally and we have APIs to fetch data from network. That’s the reason native app works faster than web apps. The App Shell works on something similar concept. It keeps your UI and resources local and pulls in content dynamically through an API.

The application shell is the minimal HTML, CSS and JavaScript required to start the app. This means the application shell is not loaded from the network every time the user visits. Only the necessary content is needed from the network. Here is the graphical representation.

Progressive Web App - App Shell

As you can see from above graphical representation, we have a app shell which will act as code repository on local and will hold all key resources of the app that is required to start the app.

To see how Google built an app shell architecture, take a look at Building the Google I/O 2016 PWA.

App shell does not work alone, it works with service worker. We will see how you can set caching of your app shell using Service worker.  App shell will cache resources offline and use it on next visit of users. It does not mean that it will not load fresh data from network. It will look for new versions of the app and will load it automatically.

Building Your App Shell

When you are building your application shell you must identify the resources that you will need to cache. You can then use service worker to cache those data and resources and load data dynamically from API. This means keep your HTML simple load all the data dynamically and build UI runtime. This way your application will load much faster. You have to determine the right balance between speed and data freshness for each of your data sources.

An application shell using Service worker is powerful pattern for offline caching but it also offers significant performance wins in the form of instant loading for repeat visits to your PWA. You can cache your application shell so it works offline and populate its content using JavaScript.

You can find more about Application Shell on Google Developers website.

Instant loading web apps with Application Shell Architecture