How to Implement a Service Worker with WorkBox in a Progressive Web App

Imagine having a web app that looks and feels just like a native mobile app. It launches from your home screen, runs in full-screen mode, and responds smoothly to your interactions. But here’s the surprising part: it wasn’t downloaded from an app sto...

Jun 23, 2025 - 21:10
 0
How to Implement a Service Worker with WorkBox in a Progressive Web App

Imagine having a web app that looks and feels just like a native mobile app. It launches from your home screen, runs in full-screen mode, and responds smoothly to your interactions. But here’s the surprising part: it wasn’t downloaded from an app store. It’s a Progressive Web App (PWA).

PWAs bring the power of the web to your fingertips with the experience of a mobile app. Even better? If you lose internet connection while on the go, the app can still function, showing your previously loaded data and getting updates once you’re back online.

In this tutorial, you’ll learn how to implement a service worker with WorkBox in a weather app using HTML, CSS, and JavaScript. We’ll start by understanding what a PWA is, the core components behind the scenes, especially service workers, and how to use Workbox to supercharge your app with offline capabilities.

Table of Contents

What We’ll Cover

  • Setting Up the Project: We'll build a simple weather app using HTML, CSS, and JavaScript. This approach is perfect for this tutorial because it keeps things simple and accessible while focusing on core PWA concepts without the added complexity of frameworks like React or Vue.

  • Turning the App into a PWA: Next, we’ll walk through the concept of a Progressive Web App, covering the key features and best practices of PWAs.

  • Implementing Service Worker via WorkBox: Finally, we’ll dive deeper into how service workers function and explore why using Workbox simplifies the process.

Here’s what the final application will look like:

Weatherly app interface showing Tokyo weather with 24°C temperature, overcast clouds, city search functionality, and location services button

Audience

This tutorial is for web developers of all levels. Whether you're new to Progressive Web Apps (PWAs) or just starting to explore service workers, this guide will walk you through the core concepts and demonstrate why using a Google-backed library like Workbox to implement service workers can be more efficient than manual implementation.

Prerequisites

Before you begin

  1. Get a free API key from the OpenWeatherAPI website

  2. Make sure you’re familiar with HTML, CSS, and JavaScript.

  3. If you’re new to PWAs, you might want to read some introductory articles to get a quick overview.

What is a Progressive Web App (PWA)?

A PWA is a web application that combines the best of web and mobile apps. It’s built using standard web technologies like HTML, CSS, and JavaScript, but it behaves and feels like a native mobile app on your phone or tablet.

Think of apps like Instagram Web, Twitter Lite, or Spotify Web Player. Even though you’re not using a native app from an app store:

  • You can still scroll your feed, view media, and send messages.

  • It works even on slow or unstable networks.

  • You can “install” it on your home screen and launch it like a regular app.

  • You even get push notifications just like a mobile app!

With PWAs, you get the reach of the web and the feel of an app without the heavy storage or installation process.

What Makes a Web App “Progressive”?

A PWA is not just any website. It’s built to progressively enhance the user experience, depending on their device and browser capabilities. Here are the core characteristics that define a PWA:

  • Responsive: Works on all screen sizes, that is, phones, tablets, and desktops.

  • Reliable: Loads instantly, even when offline or on poor networks.

  • Installable: Can be added to the home screen without needing an app store.

  • Engaging: Supports features like push notifications and background sync.

Components of a PWA

Before your web app can be considered a PWA, it must include the following:

A Web Application Manifest

The web app manifest is a JSON file that tells the browser about your web app, how it should appear, and behave when installed on a user's device.

Think of it like your app’s business card. It includes details like:

  • App name and short name – How your app is labeled on the home screen or app list.

  • Icons – Images used for app icons on different screen sizes and resolutions.

  • Theme color and background color – Defines the look of your app’s UI and loading screen.

  • Start URL – The page that opens when the app is launched.

  • Display mode – Controls whether the app opens in a browser tab, fullscreen, or a native-like window.

  • Screenshots – Optional preview images that show how your app looks on different devices in app stores or installation prompts.

A Service Worker

This is a script that runs in the background. It handles offline behaviour, caching, background sync, and push notifications needed to make your PWA function.

More details about the service worker will be discussed later in this article.

HTTPS

PWAs must be served over HTTPS. This is not optional. Here’s why:

  • It protects users by ensuring secure data transfer.

  • It enables important features like service workers and push notifications.

  • Browsers won’t allow service workers to register on non-secure origins.

If you're testing locally, you can use localhost (which is treated as secure), But for production, your site must have an SSL certificate.

What is a Service Worker in PWA?

In PWAs, a service worker is a JavaScript file that runs in the background, separate from your main app, and acts like a network proxy. It can:

  • Cache resources and serve them offline

  • Intercept network requests and apply caching strategies

  • Handle background syncs

  • Manage push notifications

Think of it as your app’s behind-the-scenes assistant—makes it load fast, works offline, and stays updated, even when you're not looking.

Why Use Workbox Instead of Manual Service Workers?

Service workers are essential in creating a PWA, but getting started with them can be challenging. Writing service worker code from scratch can often be tedious and prone to errors. For example, you'd need to:

  • Manually configure caching strategies

  • Handle service worker updates

  • Write and maintain a lot of repetitive boilerplate code

Workbox, a library from Google, makes things easier by letting developers focus on what matters, without worrying about the complicated parts of service workers.

However, it’s still important to understand how service workers function, since they handle some complex tasks under the hood.

Here are key things a service worker (with or without Workbox) does:

  • Install event: Set up cache

  • Activate event: Clean up old caches

  • Fetch event: Intercept network requests and serve from cache

With Workbox, these are wrapped in easy-to-use functions.

Introduction to WorkBox

Workbox is a collection of libraries that helps developers build efficient service workers quickly, with best practices built right in. It supports strategies like:

  • CacheFirst: Load from cache, fall back to network

  • NetworkFirst : Try network, fall back to cache

  • StaleWhileRevalidate: Serve from cache and update in the background

Understanding Workbox Modules

Workbox is more than just a tool. It is a collection of powerful modules, each designed to simplify different parts of working with service workers. These modules are flexible and can be used in three key contexts:

  • Service Worker Context – Inside your service worker file, where you handle caching, routing, and other background tasks.

  • Window Context – Inside your main application (the client-side JS), where you register and communicate with the service worker.

  • Build Tools Integration – Tools like Webpack use Workbox to generate service worker files and precache manifests during your build process.

Let’s break down some of the most popular and essential modules Workbox offers:

  1. workbox-routing

This module handles routing network requests within your service worker. Think of it like a traffic director that listens for fetch events and decides what to do with them.

Use case: Route API requests to the network while routing static asset requests to the cache.

  1. workbox-strategies

This is where caching strategies like CacheFirst, NetworkFirst, and StaleWhileRevalidate are used. It provides a clean and consistent API for handling how your app responds to different requests.

Use case: Apply different caching behaviours for images, fonts, or dynamic data with minimal code.

  1. workbox-precaching

This module handles precaching by storing static assets during the service worker’s install phase. It makes it easy to cache files ahead of time and ensures that updates are managed efficiently.

Use case: Preload essential assets (like HTML, CSS, and logo images) so your app loads instantly, even offline.

  1. workbox-expiration

It is used as a plugin alongside caching strategies. This module adds smart cache expiration. You can automatically remove old or excessive items from the cache based on how long they've been stored or how many items exist.

Use case: Keep your cache size under control without manually tracking and deleting outdated files.

workbox-window

This module is designed for the browser (window) side of your app. It simplifies service worker registration and allows you to communicate with the service worker from your page easily.

Use case: Detect when a new service worker is available and prompt the user to refresh the app to update.

You can use WorkBox via:

  • npm

  • CDN (which we'll use here for simplicity)

Project Setup

Let's start by creating our project structure:

weather-pwa/
├── index.html
├── style.css
├── js/
│   ├── app.js
│   └── install.js
├── service-worker.js
├── images/
│   └── [your image files and folders here]
├── manifest.json
├── config.js  
└── offline.html

The HTML Structure

First, let's build our index.html file:


html>
<html lang="en">
    html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="icon" href="/images/logo.png" type="image/png">
        <meta name="description" content="Simple Weather Progressive Web App" />
        <link rel="stylesheet" href="/styles.css" />
        <title>Weatherlytitle>
    head>


<body>
    <header class="header">
        <img loading="lazy" class="logo" src="images/logo.png" alt="Weatherly Logo">
        <h1>Weatherlyh1>
    header>

    <main class="main">
        <div class="weather-card">
            <div class="location-container">
                <input type="text" id="location-input" placeholder="Enter city name">
                <button id="search-btn">Searchbutton>
                <button id="locationBtn">