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 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:
Hello World Hello World!
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.