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

by Kelvin
Internet Paso a Paso

Forbes, Twitter, Uber, Le Equipe, Telegram or Instagram They are some of the giants who stepped forward and created their own PWA, or progressive applications as they are commonly known. This scenario suggests the possibility that conventional websites are forgotten.

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

  

If you don't want to be dragged through time, It is important that you start thinking about making your website progressive, or at least as close as possible, since this will begin to have weight when positioning itself sooner rather than later.

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

A progressive application is a tool programmed and written in web languages like HTML5, JavaScripts and CSS, but that behaves like a mobile application, preserving characteristics of these as having a 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 thing you are trying to do is look like the second one, but if we can identify several which make 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 for its part is cross-platform 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 its part, progressive websites rarely exceed 1MB in weight.
  • Quick Updates: If an application is very large, every time it is updated it will take a few minutes to do so. A progressive app is more versatile in that regard since being so light, updates are made in a matter of seconds.

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

A progressive application consists basically of four parts; the manifest, the service worker, the icon and the server. Each of them has a fundamental role in the structure of the entire tool.

App Manifesto

The manifesto of a PWA application it is a JSON file in which you specify all the metainformation of this. It is where the theme color, name, background color, icon and 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, these also record information to be loaded when there is a connection, which allows the app to be run 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 hallmark of the web.

HTPPS

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 HTPP like many websites currently. The most important thing about a progressive app is its security, and browsers will watch over it.

What will we need to program this progressive web application?

We are reaching the moment of truth in which we will have to get to work to create our progressive web application. 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 meet a couple of important requirements that we will have to do before we start programming. These are the following:

  • A Dark Sky API key: The data of our weather application will come directly from this API, so you must get 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 HTML5, CSS and JavaScripts languages.

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

We have reached where we wanted to arrive. It's time to start programming your first progressive application, a very simple one 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 provide 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 «KeyAqui» for the API key you just acquired. If all goes well, you should be able to see the forecast of New York City without problems.

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

Get the app code

This is actually a test lab, so we have taken a repository directly from Developers Google so you can take this guided test. To obtain this repository you need to use Glitch, a very useful platform that helps developers 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 on «New Project» and then where it says «Clone from Git Repo ».
  • That will open a small window where you will have to paste the following address «Https://github.com/googlecodelabs/your-first-pwapp.git» and click on "To accept".

open-repository-en-glitch "width =" 800 "height =" 384 "src =" https://internetpasoapaso.com/wp-content/uploads/abrir-reposititorio-en-glitch-e1564160680590.jpg "data-pagespeed -url-hash = "300248324" onload = "pagespeed.CriticalImages.checkImageForCriticality (this);" /></p><div class='code-block code-block-6' style='margin: 8px auto; text-align: center; display: block; clear: both;'><div data-ad=

  • 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 = »Password Here» and put your Dark Sky API key where it says «Password Here».

Enter-API-key-Dark-Sky "width =" 766 "height =" 368 "srcset =" https://internetpasoapaso.com/wp-content/uploads/Introucir-clave-de-API-Dark-Sky .jpg 766w, https://internetpasoapaso.com/wp-content/uploads/Introucir-clave-de-API-Dark-Sky-300x144.jpg 300w "data-lazy-sizes =" (max-width: 766px) 100vw , 766px "src =" https://internetpasoapaso.com/wp-content/uploads/Introucir-clave-de-API-Dark-Sky.jpg "data-pagespeed-url-hash =" 1988108945 "onload =" pagespeed. CriticalImages.checkImageForCriticality (this); "/></p><ul><li>Now you must click on <strong>«Show Your App»</strong> to see the application in action.</li></ul><h3><i class= Lighthouse audit

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 perform audits to 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 open Chrome DevTools and position yourself in the tab Audits Here the platform shows a list of audit categories that you should leave all enabled.
  • The next thing is to click on Execute audits and after a few seconds, Lighthouse gives you a page report.

Audit-of-the-PWA "width =" 800 "height =" 517 "src =" https://internetpasoapaso.com/wp-content/uploads/Auditoria-de-la-PWA-e1564573202784.jpg "data-pagespeed -url-hash = "778247044" onload = "pagespeed.CriticalImages.checkImageForCriticality (this);" /></p><p>In this case we will focus only on the results of the PWA section, which are the ones that interest us. <strong>It will surely throw the following problems:</strong></p><div class='code-block code-block-7' style='margin: 8px auto; text-align: center; display: block; clear: both;'><div data-ad=

Now, our mission in the following tutorial is to make all this approved, so that we make our progressive web work with and without internet connection, be installable and have a decent application manifest.

Create application manifest

The reason why the app failed the manifest is because it basically does not have one so we will have to believe it, although in your case you will simply have to modify 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 application. Then, we must notify the browser about our manifest by adding <link rel = "manifest" … to each page of our application. Now add the following line to the item in the index.html file.

 

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

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

 

Make the web offline

Now comes one of the most complicated parts of the entire guide, We will get into pure and hard programming to correctly create our service worker, an element that we mentioned earlier as indispensable for any progressive application.

All users what we expect from an app is that it can be used without an internet connection, so that it is easy for us to enter the content without being on any network. This is equally important in a progressive app, so the need for the Chrome dinosaur to never come out is imperative.

What we are going to do here is a personalized offline page. So when someone enters the app and has no connection, it is the one that is displayed instead of the annoying dinosaur. For this we will 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 for you to specialize in them. This way you will grow professionally since you will learn cutting-edge knowledge that will allow you to step forward from 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 application:

// 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 must indicate to the service worker the page that will be displayed when you are offline. Within the repository we already create a personalized offline page in (public / offline.html). What you should do is simply 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 picture:

Now the next thing we should do is add this line of code to the event «Install» to tell the service worker who patches the 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 go halfway. The next thing is to make our service worker clean the cache so that there is no old data 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 effective and in case of failure, let's be redirected to the offline page that we 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. But nevertheless, This is just the beginning of everything, there are still things to prop up.

Offer complete offline experience

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

The first thing we are going to do is change the logic of the application, what is done so that it can make asynchronous requests work correctly. These requests are one to the network and one to the cache. To do this you must go to the route 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 must make, so far it is already able to provide a more or less complete offline experience. But it is still not capable of 100% functional without internet connection.

To do this we must first pre-cache the resources of the app, 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 service worker folder, so we add the complete file list. This is done with the following code:

// CODELAB: Add list of files to cache here. const FILES_TO_CACHE = (   '/',   '/index.html',   '/scripts/app.js',   "http://internetpasoapaso.com/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', );

What we must keep in mind with this is that we must constantly update Cache_NAME when we add a new file. We have removed offline.html because at this instance our website does not need it because now it has all the necessary resources to work offline and not show a page of «No connection».

To make sure 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 these 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 experience without internet connection that we can use from any browser. We have practically all the work done, but there is still one last detail to prop up:

Make the app installable

To finish our guide, what we must do is simply that our application is installable in the browser, something that although it seems difficult is the easiest thing to do in the whole 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 to the file:

 

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

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

Then to show the install button, 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 is the time to schedule to show the prompt and hide the installation button since 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 we have created is completely installable and you have learned to do with internetpasoapaso.com that we always teach you everything you need to know about the internet and computing. We hope you find this information very useful.

If you have any questions, leave them in the comments, we will answer you as soon as possible, and it will surely be of great help to more members of the community. Thank you! ????

escort malatya escort bursa escort antalya escort konya mersin escort