DEV Community

Cover image for Building Progressive Web Apps: How to Create Offline-Capable, Installable Web Applications
Anisubhra Sarkar (Ani)
Anisubhra Sarkar (Ani)

Posted on

Building Progressive Web Apps: How to Create Offline-Capable, Installable Web Applications

Progressive Web Apps (PWAs) are web applications that combine the best features of web and native apps to deliver fast, reliable, and engaging user experiences. They are designed to work seamlessly across all devices and platforms, leveraging modern web capabilities such as service workers, offline support, installability, and push notifications.

In this guide, we’ll cover the key features of PWAs, how they work, and the technologies that make them possible, including service workers, offline support, installable apps, and push notifications.


What Are Progressive Web Apps (PWAs)?

PWAs are web applications that are:

  1. Reliable: Load instantly and work offline or in low-network conditions.
  2. Fast: Provide a smooth and responsive experience.
  3. Engaging: Feel like native apps with features like push notifications and installability.

Key Characteristics of PWAs:

  • Responsive: Work on any device and screen size.
  • Offline Capable: Use service workers to enable offline functionality.
  • Installable: Can be installed on a user’s device via a browser.
  • Secure: Served over HTTPS to ensure data integrity and security.
  • Discoverable: Indexed by search engines like regular web apps.
  • Linkable: Can be shared via URLs without needing app stores.

Key Technologies Behind PWAs

1. Service Workers

A service worker is a JavaScript file that runs in the background of your web application, separate from the main browser thread. It enables powerful features such as caching, offline support, and push notifications.

Key Features of Service Workers:

  • Caching: Store resources locally to enable offline functionality.
  • Background Sync: Sync data in the background when the network becomes available.
  • Push Notifications: Deliver real-time notifications even when the app is closed.

How Service Workers Work:

  1. A service worker is registered by the app.
  2. It intercepts network requests and decides whether to serve cached or network resources.
  3. It runs in the background, enabling offline support and background tasks.

Example: Registering a Service Worker

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(() => {
      console.log('Service Worker registered successfully!');
    })
    .catch((error) => {
      console.error('Service Worker registration failed:', error);
    });
}
Enter fullscreen mode Exit fullscreen mode

Example: Basic Service Worker

self.addEventListener('install', (event) => {
  console.log('Service Worker installing...');
  event.waitUntil(
    caches.open('pwa-cache').then((cache) => {
      return cache.addAll([
        '/',
        '/index.html',
        '/styles.css',
        '/script.js',
        '/logo.png',
      ]);
    })
  );
});

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

2. Offline Support

Offline support is one of the defining features of PWAs. By caching assets using service workers, PWAs can provide functionality even when there is no network connection.

How Offline Support Works:

  1. When the app is first loaded, the service worker caches key assets (HTML, CSS, JavaScript, images).
  2. When offline, the browser serves the cached assets instead of trying to fetch them from the network.

Benefits of Offline Support:

  • Improves user experience in low or no connectivity environments.
  • Reduces server load by serving cached files.

Example: Caching Resources for Offline Support

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

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request).catch(() => caches.match('/offline.html'));
    })
  );
});
Enter fullscreen mode Exit fullscreen mode

3. Installable Apps

PWAs can be installed on a user’s device, just like a native app, without relying on app stores. Once installed, they appear on the home screen and can be launched like traditional apps.

How Installability Works:

  1. Manifest File: A JSON file (manifest.json) provides metadata about the app (e.g., name, icons, start URL).
  2. Add to Home Screen: Browsers prompt users to install the PWA if certain criteria are met (e.g., HTTPS, service worker, manifest).

Example: Manifest File

{
  "name": "My PWA",
  "short_name": "PWA",
  "start_url": "/index.html",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [
    {
      "src": "/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Benefits of Installability:

  • PWAs behave like native apps but are built with web technologies.
  • No need for app store submission.
  • Reduce friction for users by allowing direct installation from the browser.

4. Push Notifications

Push notifications allow PWAs to send real-time updates to users, even when the app is not actively running. This feature enhances engagement and user retention.

How Push Notifications Work:

  1. The service worker subscribes to the Push API.
  2. Notifications are sent from the server to the service worker.
  3. The service worker displays the notification to the user.

Example: Subscribing to Push Notifications

navigator.serviceWorker.ready.then((registration) => {
  registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: '<Your_Public_Key>'
  }).then((subscription) => {
    console.log('Push subscription:', subscription);
  }).catch((error) => {
    console.error('Push subscription failed:', error);
  });
});
Enter fullscreen mode Exit fullscreen mode

Example: Displaying Notifications in Service Worker

self.addEventListener('push', (event) => {
  const data = event.data.json();
  self.registration.showNotification(data.title, {
    body: data.body,
    icon: '/icon.png',
  });
});
Enter fullscreen mode Exit fullscreen mode

Benefits of Progressive Web Apps

  1. Improved User Experience:
    • PWAs load quickly and work offline, ensuring a smooth experience.
  2. Cross-Platform Compatibility:
    • PWAs run across all devices and platforms using a single codebase.
  3. Reduced Development Costs:
    • Build one app for both web and mobile instead of separate native apps.
  4. No Installation Friction:
    • Users can install PWAs directly from the browser without visiting app stores.
  5. SEO-Friendly:
    • PWAs are indexed by search engines, unlike native apps.

Example Workflow for Building a PWA

  1. Create the App Shell:
    • Build the basic HTML, CSS, and JavaScript structure of your app.
  2. Add a Service Worker:
    • Register a service worker and implement caching for offline support.
  3. Create a Manifest File:
    • Define metadata like name, icons, and start URL for installability.
  4. Enable HTTPS:
    • Ensure your app is served over HTTPS for security.
  5. Test and Optimize:
    • Use tools like Lighthouse to test your PWA’s performance and compliance.
  6. Add Push Notifications (Optional):
    • Implement push notifications for real-time engagement.

Tools for Building PWAs

  1. Workbox: A library for simplifying service worker implementation.
  2. Lighthouse: A tool for auditing PWA performance and best practices.
  3. Webpack: Use plugins for managing service workers and caching.
  4. Browsers: Test your PWA in modern browsers like Chrome, Edge, and Firefox.

Conclusion

Progressive Web Apps (PWAs) are transforming the way we build and deliver web applications by offering the reliability, speed, and engagement of native apps while retaining the flexibility of the web. Key technologies like service workers, offline support, installability, and push notifications make PWAs an excellent choice for businesses looking to enhance their user experience and reduce development costs.

By leveraging PWAs, you can create applications that are fast, reliable, and accessible to users across devices and platforms.

Top comments (0)