Build a Basic PWA With Html and Javascript for Beginners

A Progressive Web App (PWA) is a web app that uses modern web capabilities to deliver a native app-like experience to users. These apps meet certain requirements , are deployed to servers, accessible through URLs, and indexed by search engines.
A Progressive Web App (PWA) works like any other normal app but with a lot of added features and a lot less hassle. They are fast, reliable, and can work perfectly in an offline environment.

In this tutorial, 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.

Creating a Basic PWA

1. The Setup

First of all, you have to create a directory for the app and add js, css, 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.

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.

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.

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.

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.

The guide to this is the end! Hope you enjoyed this tutorial.

Learn More

Thanks for reading !

#pwa #javascript #js #html

Build a Basic PWA With Html and Javascript for Beginners
2 Likes83.35 GEEK