How to build a basic PWA with HTML and Javascript

by Janeth Kent Date: 10-04-2020 pwa html javascript tutorial


Looking at the web for a basic PWA online training exercise, everything I found was just too confused or required libraries/system/stage or another.

If we need to learn another innovation, we would preferably not get derailed with redundant subtleties ...

We have indeed composed a basic introductory exercise to draw from different sources, which would not require external sources. Personally, I would prefer not to be distracted with irrelevant details when I learn a new technology.

In case you're not familiar with Progressive Web Apps the essential thought is to utilize browser technologies to build a web application that works offline and has the look and feel of a native application. In this exercise, we'll tell you the best way to to make the most straightforward application conceivable, that works without an internet connection, and can be added to your home screen.

You should know HTML, CSS, and JavaScript to get the most out of this tutorial. If you can code a web page and add some interactivity using plain-vanilla JavaScript, you should be able to follow. You'll need a text editor, the latest Chrome version and a local web server to build this app.

In this tutorial, we used Adobe's NetBeans, because it has a web server built, but you can use any text editor you’re comfortable with.

Phase 1: The Setup

First of all, you have to create a directory for the app and add jscss, and images subdirectories. It should look like this when you’re finished:

/Hello-PWA   # Project Folder
/css     # Stylesheets
/js      # Javascript
/images  # Image files.

Open your project folder in Brackets to get started.

When writing the markup for a Progressive Web App there are 2 requirements to keep in mind:

1. Even if JavaScript is disabled, the app should keep showing some content. This prevents users from viewing a blank page if their internet connection is poor or if an older browser is used.

2. It should be responsive to a variety of devices and display properly. In other words, it must be mobile-friendly.

We will address the first requirement for our basic app by simply hard-coding the content and the second by adding a meta tag for the viewport. To do this, create an index.html file in the root folder of your project and add the following markup:

<!doctype html>
<html lang="en"> 
<head>   
<meta charset="utf-8">
<title>Hello World</title> 
<link rel="stylesheet" href="css/style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body class="fullscreen">
<div class="container">   
<h1 class="title">Hello World!</h1> 
</div>
</body>  
</html>

Second step: create a file named style.css in the css folder, such as:

body {font-family: sans-serif;} 
html, .fullscreen {display: flex;height: 100%; margin: 0;padding: 0;width: 100%; }  
.container {margin: auto;text-align: center;} 
.title {font-size: 3rem;}

The app can now be tested by clicking on the text editor preview button. This will open a browser window and serve up your page.

Phase 2: Testing

Now that we have our "Hello world" the browser, we're going to use Google's Lighthouse to test the app and see how well it meets PWA standards. Press F12 to open the Chrome developer panel and click on the Lighthouse audit tab

Make sure you check the option "Progressive Web App. " For now, you can uncheck the others. Then click on the button "run tests. " Lighthouse should give you a score and a list of audits that the app has passed or failed after a minute or two. At this point, the app should score about 45. If everything has been properly coded, you will notice that most of the tests carried out are related to the requirements we outlined at the beginning:

1. If JavaScript is not available, our basic app contains some content.

2. Has a wide or initial scale tag.

3. The content of the viewport is correctly sized.

Phase 3: Add a Service Worker

Our app's next requirement is to register a service worker. Service workers are basically scripts that perform tasks that do not require user interaction in the background. This launches your users ' main app while the service worker takes care of mundane things.

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available). A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker. Service workers only run over HTTPS, for security reasons. Having modified network requests, wide open to man in the middle attacks would be really bad. In Firefox, Service Worker APIs are also hidden and cannot be used when the user is in private browsing mode.

For our app, we’ll use one to download and cache our content and then serve it back up from the cache when the user is offline.

Now, create a file named sw.js in the root folder and attempt to enter the contents of the following script. The reason it is stored in the root of the app is to give it access to all files of the app. This is because service workers only have access to files in the same directory and subdirectories.

var cacheName = 'hello-pwa'; 
var filesToCache = [
'/',    
'/index.html',    
'/css/style.css',  
'/js/main.js'  ];  
self.addEventListener('install', function(e) { 
e.waitUntil(
caches.open(cacheName).then(function(cache) { 
return cache.addAll(filesToCache);   
})    
);  
}); 
/* Serve cached content when offline */ 
self.addEventListener('fetch', function(e) {  
e.respondWith(      caches.match(e.request).then(function(response) {  
return response || fetch(e.request);
})   
);  
});

The script's first lines declare two variables: cacheName and files ToCache.

CacheName is used to create access of an offline cache from Javascript in the browser. FilesToCache is an array that contains a list of all cached files. These files should be written as URLs. Note that the first is just "/, "the base URL.

This means that the browser caches index.html even if the user does not type the file name directly.

Next, we add a function to install the service worker and use cacheName to create the browser cache. Once the cache has been created, all the files listed in the ToCache array will be added. Please keep in mind that while this code is used for demonstration purposes, it is not intended for production, as it will stop if even one of the files is not loaded.)

Finally, we add a function to load in the cached files when the browser is offline.

Finally, when the browser is offline, we add a function to load into the cached files.

We need to register the service worker with our app now.

In the js folder, create a file named main.js and enter the following code:

window.onload = () => {  
'use strict';     
if ('serviceWorker' in navigator) {     
navigator.serviceWorker  
.register('./sw.js'); 
} 
}

This code simply loads up the service worker script and gets it started.

Now, add the code to your app by adding the script to index.html just before the tag < /body > closes.

</div>
<script src="js/main.js"></script>
</body>

 index.html should look like this:

<!doctype html>  
<html lang="en">  
<head>     
<meta charset="utf-8">  
<title>Hello World</title>  
<link rel="stylesheet" href="css/style.css">     
<meta name="viewport" content="width=device-width, initial-scale=1.0">   
</head>   
<body class="fullscreen">    
<div class="container">     
<h1 class="title">Hello World!</h1>   
</div>   
<script src="js/main.js"></script>   
</body>   
</html>

If you now run the Lighthouse audits, your score should rise to 64 and the service worker requirement passes.

Phase 4: Add a Manifest

The ultimate requirement for a PWA is a manifest file. The manifest is a json file that specifies how the app looks and acts on devices. For instance, the orientation and theme color of the app can be set.

In your root folder, save a file called manifest.json and add the following content:

{  
"name": "Hello World",   
"short_name": "Hello", 
"lang": "en-US",     
"start_url": "/index.html", 
"display": "standalone",  
"background_color": "white",   
"theme_color": "black" 
}

We set the title, background and theme colors for our app and tell the browser that it should be treated as an independent app without the chrome browser.

The fields are line by line as follows:

name 
The app's title/name. This is used when the user is asked to install the app. It should be the app's full title.

short_name 
Is the name of the app as shown on the icon app. It should be short.

lang
The default language the app is geo-localized (en-Us in our case)..

start_url
When the app is launched, tell the browser which page to load. It's generally index.html.

display
The shell type should be shown in the app. We use our app to look and feel like a standard native app on our own. Other settings are available to complete the screen or include the chrome browser.

background_color
The color of the splash screen that opens when the app launches.

theme_color
Sets the color of the toolbar and in the task switcher.

Now, add the manifest to your app:

<head>
...
<link rel="manifest" href="/manifest.json">
...
</head>

You should also declare the theme color to match the one set in your manifest by adding a meta tag inside the head:

<meta name="theme-color" content="black"/>

App Icons

You may have noticed that Lighthouse is complaining about missing app icons after the previous step. Although the app is not strictly required to work offline, it allows your users to add the app to their home screen.

Add the icons to your manifest file after the short_name property.

And now. add them to index.html.

Phase 5: Finish!

The coding is finished at this point and the last thing to do is upload the application to a web server!

Hope you enjoyed this tutorial.

Original content James Johnson Vector created by freepik - www.freepik.com

 
by Janeth Kent Date: 10-04-2020 pwa html javascript tutorial hits : 34711  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.

 
 
 

Related Posts

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

Loading images by resolution with HTML5

Normally the way to load images in HTML is through the img element to which we pass as a parameter the URL of the image to load. But since HTML5…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration