Skip to content
Step by Step Internet 🌐 Guides for learning to surf the Net

How to create a Progressive WEB Application (PWA) from scratch with basic programming knowledge? step by step guide

UPDATED ✅ Do you need to create a Web Progressive App from scratch and don’t know how to do it? ⭐ ENTER HERE ⭐ and discover how ✅ EASY and FAST ✅

Forbes, Twitter, Uber, Le Equipe, Telegram or Instagram are some of the giants that have stepped forward and created their own PWAs, or progressive apps as they are commonly known. This scenario suggests the possibility that conventional websites will be forgotten.

It is normal, the websites as we know them have been evolving more and more until they become less powerful replicas than the native applications. A PWA is basically the product of that evolution.which has now found a way to offer a mobile app-like experience from any browser.

If you don’t want to be dragged down by time, it is important that you start thinking about making your website progressive, or at least as close to one as possibleas this will start to weigh on positioning sooner rather than later.

What is a progressive web app and how is it different from a native one?

A progressive application is a tool programmed and written in web languages such as HTML5, JavaScripts and CSS, but that behaves like a mobile applicationkeeping their characteristics such as having storage on the device, which allows it to be used without an internet connection.



The differences between a progressive and a native are not many, since the first one is precisely trying to resemble the second onebut if we can identify several What makes us prefer one over the other?

  • Multi platform: the main difference between one and the other is the fact that the native application can only be used on the device on which it is installed, so to use it on another you will have to download it from scratch. The web application, on the other hand, is multiplatform since you can access it from any browser as if it were a website.
  • Weight: Currently we can find native applications as heavy as a computer program, so this depends on the power. For their part, progressive websites rarely exceed 1MB in weight.
  • Quick updates: if an application is very large, each time it is updated it will take a few minutes to do so. A progressive app is more versatile in that sense since, being so light, its updates are made in a matter of seconds.

Components of a PWA What does it take to make one?

A progressive app is basically made up of four parts; the manifest, the service workers, the icon, and the server. Each of them has a fundamental role in the structure of the entire tool..

App Manifest

The manifesto of a PWA app is a JSON file in which all the meta information of this. It is where the color of the theme, the name, the background color, the icon and those details are indicated.

Service Worker

This is perhaps the most important component. As we mentioned before, these are a programmatic element that offers solutions for the exchange of information between the network and the browser cache.. In addition, they also record information so that it is loaded when there is a connection, which allows the app to be executed without internet.

Icon

The icon is nothing more than the image that will identify your application from the other web applications on the market, you must design it yourself since this will be the distinctive of the web.

HTTPS

Finally, it will be necessary to have a secure server with its corresponding SSL certificate. Browsers will never run a PWA that is hosted on an HTTP like many websites currently do. The most important thing about a progressive app is its security, and browsers will ensure it.

What will we need to program this progressive web application?

We’re getting to the moment of truth where we’ll need to get down to business building our Progressive Web App. This will be nothing more than a simple weather forecaster that will tell you the temperature, humidity and atmospheric pressure.

To be able to create it, it will be necessary that we first meet a couple of important requirements that we will have to carry out before starting to program. These are the following:

  • A Dark Sky API key: the data of our weather application will come directly from this API, so you must obtain a key from it. These are completely free for small non-profit projects like the one we are going to create.
  • programming knowledge: we are not going to deceive you, in order to understand what we are going to tell you, you must at least understand web programming and the most essential of the HTML5, CSS and JavaScript languages.

Steps to create a progressive web application that works with and without the internet

We have reached where we wanted to go. It’s time for you to start programming your first progressive appa very simple one but that will give you the necessary knowledge to create a more complete and powerful one in the future. Pay attention and follow all the steps carefully:

Get the Dark Sky API

As we mentioned before, the first thing you should do is get a Dark Sky API key, which will be the one that provides the weather data to our progressive app. To do this you must go directly to https://darksky.net/dev, register and request the key.

Once you have it, you should check that it works perfectly. To do this you must take the following link and replace where it says “PasswordHere” by the API key you just acquired. If all goes well, you should be able to see the forecast for New York City with no problem.

https://api.darksky.net/forecast/ClaveAqui/40.7720232,-73.9732319

Get the app code

This is actually a test lab, so we’ve pulled a repository directly from Developers Google for you to run this guided test on. To obtain this repository you need to use Glitch, a very useful platform that allows developers to exchange information without problems.

What you should do is the following:

  • go to glitch.com and in the upper right corner of the screen click “New Project” and then where it says clone from GitRepo”.
  • That will open a small window in which you will have to paste the following address https://github.com/googlecodelabs/your-first-pwapp.git and click “To accept”.

open-repository-in-glitch

  • In that repository is all the information you need. Now you must go to the .env file and modify where it says DARKSKY_API_KEY=”KeyHere” and put your Dark Sky API key where it says “KeyHere”.

Enter-API-Key-Dark-Sky

  • Now you need to click “Show Your App” to see the app in action.

Audit with Lighthouse

Basically with that code the PWA is completed, but it still has flaws that we must correct ourselves and that we will discover thanks to this audit. This tool has a section specially designed to audit progressive websites like the one we are creating and for this we must do the following:

  • Open your project in a new tab in your Chrome browser.
  • later opens Chrome DevTools and position yourself in the tab audits. Here the platform shows a list of audit categories that you must leave all enabled.
  • The next thing is to click on Run audits and after a few seconds, Lighthouse gives you a report of the page.

PWA-Audit

In this case we will focus only on the results of the PWA section, which are the ones that interest us. It will surely throw the following problems:

  • ❗FAILED: The current page does not respond with a 200 when offline.
  • ❗FAILED: start_url it doesn’t respond with a 200 when offline.
  • ❗FAILED: It does not register a service worker that controls the page and start_url
  • ❗FAILED: The web application manifest does not meet the installation requirements.
  • ❗FAILED: It is not configured for a custom home screen.
  • ❗FAILED: Does not set a theme color for the address bar.

Now our mission in the next tutorial is to get all of this approved, so let’s make our progressive web works online and offline, is installable, and has a decent app manifest.

Create app manifest

The reason the app failed the manifest is because it basically doesn’t have one so we’ll have to create it, although in your case you will simply have to modify a bit the base code of a manifest that we have prepared for you.

{
  "name": "Clima",
  "short_name": "Clima",
  "icons": [{
    "src": "/images/icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png"
    }, {
      "src": "/images/icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png"
    }, {
      "src": "/images/icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png"
    }, {
      "src": "/images/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    }, {
      "src": "/images/icons/icon-256x256.png",
      "sizes": "256x256",
      "type": "image/png"
    }, {
      "src": "/images/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }],
  "start_url": "/index.html",
  "display": "standalone",
  "background_color": "#3E4EB8",
  "theme_color": "#2F3BA2"
}

To add this manifest to your app. Next, we need to notify the browser about our manifest by adding <link rel="manifest"... to each page of our application. Now add the following line to the element <head> in the File index.html.

<!-- CODELAB: Add link rel manifest -->
<link rel="manifest" href="/manifest.json">

Later we must add a meta description to our application. For this we must simply add the following line of code to the application header:

<meta name="description" content="Un simple aplicación meteorológica">

Finally we set the color of the address bar of our progressive applicationfor which you must copy the following line of code in the of your application.

<!-- CODELAB: Add meta theme-color -->
<meta name="theme-color" content="#2F3BA2" />

Make the website offline

Now comes one of the most complicated parts of the whole guide, Well, we will get into pure and simple programming to correctly create our service workeran element that we mentioned earlier as essential for any progressive application.

What all users expect from an app is that it can be used without an internet connection, so that it is easy for us to access the content without being on any network. This is just as important in a progressive app, so the need for the dinosaur to never leave Chrome is imperative.

What we are going to do here is a custom offline page. So that when someone enters the app and has no connection, it is the one that is displayed instead of the annoying dinosaur. For this we are going to create our first service worker.

If you are not very familiar with them we recommend that you do so. This is a whole new universe in the world of programming for you, so it is very convenient that you specialize in them. This way you will grow professionally since you will learn cutting-edge knowledge that will put you one step ahead of your guild..



The first thing we are going to do is register the service worker, for which you will have to add the following line of code to the Index file of the progressive app:

// CODELAB: Register service worker.
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js')
        .then((reg) => {
          console.log('Service worker registered.', reg);
        });
  });
}

Now you need to tell the service worker which page to display when offline. Within the repository we already created a personalized offline page in (public/offline.html). What you have to do is just go to public/service-worker.js in the repository and in the const section “FILES_TO_CACHE = [
];” include the value “offline.html”. It should look like in the image:

indicate offline page

Now the next thing we need to do is add this line of code to the event “install” to indicate to service worker patching progressive web offline:

evt.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      console.log('[ServiceWorker] Pre-caching offline page');
      return cache.addAll(FILES_TO_CACHE);
    })
);

So far we are halfway there. The next thing is to make our service worker able to clean the cache so that there is no old data left in it. That is why we have to add this code in the public/service-worker.js folder:

// CODELAB: Remove previous cached data from disk.
evt.waitUntil(
    caches.keys().then((keyList) => {
      return Promise.all(keyList.map((key) => {
        if (key !== CACHE_NAME) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
);

Finally, we are going to add another line of code to make the service worker’s network requests more efficient and in case one fails, we will be redirected to the offline page that we have mentioned above. What you should do is add the following in the folder public/service-worker.js:

// CODELAB: Remove previous cached data from disk.
evt.waitUntil(
    caches.keys().then((keyList) => {
      return Promise.all(keyList.map((key) => {
        if (key !== CACHE_NAME) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
);

With this we will have created a tool that provides a fairly basic offline experience but that perfectly meets the requirements of a progressive app. Nevertheless, this is just the beginning of everything, there are still things to shore up.

Offer complete offline experience

To better understand this, it is very important that you investigate the life cycle of a service workersince these steps are closely related to that.

The first thing we are going to do is change the logic of the application, which is done so that it can make asynchronous requests work correctly. These requests are one to the network and one to the cache. For this you must go to the path public/scripts/apps and modify the following line of code:

// CODELAB: Add code to get weather forecast from the caches object.
if (!('caches' in window)) {
  return null;
}
const url = `${window.location.origin}/forecast/${coords}`;
return caches.match(url)
    .then((response) => {
      if (response) {
        return response.json();
      }
      return null;
    })
    .catch((err) => {
      console.error('Error getting data from cache', err);
      return null;
    });

Now the next thing is to modify the element updatedata, which is lower than the previous one. For it We modify the code as follows:

// CODELAB: Add code to call getForecastFromCache.
getForecastFromCache(location.geo)
    .then((forecast) => {
      renderForecast(card, forecast);
    });

With this we have already solved the problem of asynchronous requests that you have to makeso far it is already capable of providing a more or less complete offline experience. But still not able to 100% functional without internet connection.

To do this, we must first precache the app’s resources, which is done by adding a Data_Cache_NAME in the folder public/service-worker. We do that with the following code:

// CODELAB: Update cache names any time any of the cached files change.
const CACHE_NAME = 'static-cache-v2';
const DATA_CACHE_NAME = 'data-cache-v1';

Now, the next thing is to update the File_TO_CACHE in the same folder as the service workers, so we add the full list of files. This is done with the following code:

// CODELAB: Add list of files to cache here.
const FILES_TO_CACHE = [
  '/',
  '/index.html',
  '/scripts/app.js',
  '/scripts/install.js',
  '/scripts/luxon-1.11.4.js',
  '/styles/inline.css',
  '/images/add.svg',
  '/images/clear-day.svg',
  '/images/clear-night.svg',
  '/images/cloudy.svg',
  '/images/fog.svg',
  '/images/hail.svg',
  '/images/install.svg',
  '/images/partly-cloudy-day.svg',
  '/images/partly-cloudy-night.svg',
  '/images/rain.svg',
  '/images/refresh.svg',
  '/images/sleet.svg',
  '/images/snow.svg',
  '/images/thunderstorm.svg',
  '/images/tornado.svg',
  '/images/wind.svg',
];

The thing to keep in mind with this is that we need to constantly update Cache_NAME when we add a new file. We have removed offline.html because at this point our website does not need it because now it has all the necessary resources to work offline and not show a page again. “no connection”.

To ensure that our event “activate” do not delete any type of file, we must change the value “if (key !== CACHE_NAME) {“ by “if (key !== CACHE_NAME && key !== DATA_CACHE_NAME) {“. In our Service-worker.js folder.

The next step in our programming is make sure the app saves weather forecasts so you can access them more easily in the future. For this you will have to add the following in the service-worker.js file:

// CODELAB: Add fetch event handler here.
if (evt.request.url.includes('/forecast/')) {
  console.log('[Service Worker] Fetch (data)', evt.request.url);
  evt.respondWith(
      caches.open(DATA_CACHE_NAME).then((cache) => {
        return fetch(evt.request)
            .then((response) => {
              // If the response was good, clone it and store it in the cache.
              if (response.status === 200) {
                cache.put(evt.request.url, response.clone());
              }
              return response;
            }).catch((err) => {
              // Network request failed, try to get it from the cache.
              return cache.match(evt.request);
            });
      }));
  return;
}
evt.respondWith(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.match(evt.request)
          .then((response) => {
            return response || fetch(evt.request);
          });
    })
);

After doing all this we will have a progressive application that offers a complete offline experience that we can use from any browser. We practically have all the work done, but there is still one last detail to shore up:

Make the app installable

To finish our guide, what we must do is simply make our application installable in the browser, something that, although it may seem difficult, is the easiest thing to do in the entire process that we have taught you so far.

The first thing we are going to do is add the file install.js ours index.html, what It is achieved by copying this code into the file:

<!-- CODELAB: Add the install script here -->
<script src="/scripts/install.js"></script>

Now we must go to the event of install.js and write the following line of code to continue with process of making our app installable:

// CODELAB: Add event listener for beforeinstallprompt event
window.addEventListener('beforeinstallprompt', saveBeforeInstallPromptEvent);

Then for the install button to be displayed, which is basic in all this, we must continue modifying our install.js with the following code:

// CODELAB: Add code to save event & show the install button.
deferredInstallPrompt = evt;
installButton.removeAttribute('hidden');

Now it’s time to program to show the prompt and hide the install button as this can only be done once. So following in the install.js file we add the following:

// CODELAB: Add code show install prompt & hide the install button.
deferredInstallPrompt.prompt();
// Hide the install button, it can't be called twice.
evt.srcElement.setAttribute('hidden', true);

Ready, now the progressive application that we have created is completely installable and you have learned how to do it with internetpasoapaso.com that we always teach you everything you need to know about the internet and computers. We hope this information will be very useful to you.

Applications