PWA Tutorial (Progressive Web Application) Beginner

What is a Progressive Web Application (PWA)?

Nowadays, the use of web applications is increasingly widespread and important. One concept that can help improve user experience is the Progressive Web Application or PWA tutorial. PWA is a concept that can combine web applications and mobile applications, is fast, responsive, and can be accessed offline.

Progressive Web Applications are like web applications that you can access via a browser as usual, but it’s can be offline. What makes the PWA special are designed to feel like native apps on your phone or computer.



How to Create a PWA?

To create a PWA, there are three main parts that we need to understand:

  1. Manifest
  2. Service Worker
  3. Registrasi Service Worker.

Apart from that, make sure you also provide the index.html file or root file of the web application. Let’s say, your root file of the web is index.html.



1. Manifest (manifest.json)

Manifest is a kind of “identity” of your PWA. In the manifest, we can specify the name, description, icon, and how the application should be displayed. Now, create a file called manifest.json, then fill it with the following code:

manifest.json:

{
  "name": "My PWA",
  "short_name": "PWA",
  "description": "Aplikasi PWA sederhana",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [
    {
      "src": "/path/to/icon.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ]
}

Open the index.html file, then insert the manifest.json location file into the index.html file with the command:

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

So, the code will look like this:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="manifest" href="/manifest.json">
</head>
<body>

</body>
</html>


2. Service Worker (service-worker.js)

Service workers are like little servants that live in the background of your application. Its job is to store data and manage requests from the internet. This allows your application to continue running even if the internet connection is slow or down.

For example, the service worker will download everything in ‘/‘, ‘/index.html‘, ‘/styles.css‘, and ‘/app.js‘, then store it in the cache so that you can see the program code like this:

service-worker.js:

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('my-cache').then(cache => {
      return cache.addAll([
        '/',
        '/index.html',
        '/styles.css',
        '/app.js'
      ]);
    })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

The service worker code should be placed in the root directory of your website. If you store it in a different directory, make sure to adjust the path when registering the service worker.



3. Registrasi Service Worker (app.js)

It’s like telling the device, “Hey, I have a service server ready to work!” This code should be placed in your app’s main JavaScript file.

app.js:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(registration => {
      console.log('Pelayan Layanan terdaftar dengan cakupan:', registration.scope);
    })
    .catch(error => {
      console.log('Pendaftaran Pelayan Layanan gagal:', error);
    });
}

So, in general, your directory layout could look like this:

root/
|-- index.html
|-- manifest.json
|-- service-worker.js
|-- app.js
|-- styles.css
|-- path/
|   |-- to/
|       |-- icon.png
|-- ...

Now, add app.js to index.html so the document root can recognize it with the command:

    <script src="/app.js"></script>

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="manifest" href="/manifest.json">
    <script src="/app.js"></script>
</head>
<body>

</body>
</html>



PWA Testing

Also ensure that your website uses the HTTPS protocol to fully enable PWA features, such as access to background service servers.

When your PWA is first loaded, the order of files executed is as follows:

  1. Service Worker (service-worker.js)
    Service workers are JavaScript scripts that run in the background and are responsible for managing cache and network interactions. When your page first loads, the browser will try to register the service worker by loading the service-worker.js file and running the code within it.
  2. Manifest (manifest.json)
    A manifest is a metadata file that provides information about your application to the browser. The browser will read the manifest when the page loads and use it to figure out how to display the app visually, such as icons, names, descriptions, and more.
  3. Root File (eg: index.html):
    Once the service worker is registered and the manifest is read, the browser will load the main page of your website, such as the index.html file. This is the page that will be displayed to the user, and it may refer to other CSS (styles.css) and JavaScript (app.js) files needed to organize the appearance and interactions on the page.

Also read: How to make a browser in fullscreen mode using Javascript?

Once you have taken all the necessary steps to implement a Progressive Web Application (PWA), there are several signs you can look for to ensure that your website has successfully implemented a PWA:

  1. Testing in Browser
    Open your website in a browser (ideally Chrome or a browser that supports PWA features well). You should see signs that the PWA is working. You can right-click on the page, then select “Inspect” and switch to the “Application” tab to see how the PWA behaves. There you will see the manifest view, service worker status, and cache used.
  2. Registered Service Worker
    When you open your website, check your browser console (usually in the “Console” or “Console” tab when you use the Inspection tool) to make sure there are no errors related to service worker registration. You should see a confirmation message that the service server has been registered.
  3. Offline Mode
    Try to turn off the internet connection or use the “Offline” feature in the Inspection tool. When you try to access a web page in an offline state, if the web page still loads properly or shows certain elements (such as images or text) even without an internet connection, it indicates that you have successfully implemented offline mode via a service worker.
  4. Access Via URL / Shortcut
    Try accessing your website via a direct URL (for example, https://www.websitename.com/) or creating a shortcut on your device’s home screen (if you’re using a mobile device). If it looks similar to the native app, functions well, and can even be accessed offline, then it’s a sign that your PWA has been successful.
  5. Splash Screen Display (Optional)
    If you have configured your manifest correctly, you may see a “splash screen” or splash screen when you open your PWA via a mobile device.

PWA + Laravel

If you want add PWA into Laravel PHP Framework, please read here.

Keep in mind that some PWAs’ appearance and behavior may vary depending on the browser and device you use. If you want to do more in-depth testing, you can use a tool like Lighthouse (under the “Audits” tab in Chrome DevTools) to audit the quality of your PWA and get further recommendations. Be sure to test across a variety of devices and connection situations to ensure your PWA functions well in a variety of scenarios. Hopefully, this PWA tutorial article is useful.

More in web.dev.

Similar Posts