Service Workers: Browser‑Based Network Proxy
Service workers are scriptable network proxies that run in the background of a web browser, allowing developers to intercept network requests, cache resources, and enable offline functionality. By operating on a separate thread from the main page, they improve performance, reliability, and user experience across modern web applications.
Lifecycle Overview
The service worker lifecycle consists of three distinct phases-install, activate, and fetch-each triggered by specific events. Understanding these phases ensures that caching strategies, version control, and request handling are applied correctly, resulting in predictable behavior and smooth updates for end users.
Installation Phase
When the install event fires, the worker typically opens a Cache Storage instance and pre‑caches essential assets. This step guarantees that core files are available even when the network is unavailable.
Activation Phase
During the activate event, the new worker takes control of pages and can purge outdated caches. Cleaning up old versions prevents storage bloat and ensures that users receive the latest resources.
Fetch Handling
The fetch event intercepts outgoing requests. The worker first checks the cache if a matching response exists, it returns that copy, otherwise it forwards the request to the network. This pattern enables offline browsing and reduces latency.
Implementation Guide
This section walks through creating a minimal service‑worker‑enabled web app, configuring HTTPS on a Vultr instance, and registering the worker from JavaScript. Secure origins are required, so Nginx with Lets Encrypt certificates is used to serve the site over HTTPS.
Project Structure and Files
The application consists of four core files:
- index.html - basic markup with a heading and link.
- main.css - simple styling for layout and colors.
- app.js - checks for
serviceWorkersupport and registers/sw.js. - sw.js - implements install, activate, and fetch event listeners.
Registering the Service Worker
The registration script first verifies that "serviceWorker" in navigator. Upon page load it calls navigator.serviceWorker.register('/sw.js'), then logs the workers state (installing, waiting, or active) and alerts the registration scope. Errors are caught and displayed to the user.
Deploying on Vultr with Systemd
After provisioning a Vultr droplet, install Nginx, obtain a Lets Encrypt certificate, and place the project files in the web root. To serve the app without a full Node.js stack, a lightweight Python HTTP server runs under systemd, guaranteeing automatic start on boot and easy management.
Python HTTP Server Script
import http.server
import socketserver
import os
PORT = 8000
DIRECTORY = "sample"
sample_dir = os.path.join(os.path.abspath(__file__), "..", DIRECTORY)
mime_types = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
}
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def guess_type(self, path):
_, ext = os.path.splitext(path)
return mime_types.get(ext.lower(), "application/octet-stream")
Handler = MyHTTPRequestHandler
os.chdir(sample_dir)
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("Serving at port", PORT)
httpd.serve_forever()
Systemd Service Definition
[Unit]
Description=Daemon for Sample Demo Application
After=network.target
[Service]
User=example_user
Group=example_user
WorkingDirectory=/home/example_user/sample
ExecStart=/usr/bin/python3 /home/example_user/http_server.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
Enable and start the service with sudo systemctl enable --now pythonserver. Verify its status using systemctl status pythonserver. This setup mirrors the approach described in the structured workflow guide and benefits from the same reliability principles used in a real‑time orchestration framework.