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 : 36197  
 
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 upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

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…

Clicky