A Simple PWA
A simple PWA explains how to build a progressive web app that can be installed on desktop or mobile and works offline. The article includes the file structure, the code for the main page, CSS styles, a JavaScript file for interactivity and service worker registration, plus the manifest file for installation. It's a step-by-step guide for beginners who want to quickly test a working PWA.
A PWA (Progressive Web App) is a web application that can be installed on desktop or mobile and works offline. Here's a simple example:
1. File structure
simple-pwa/
├── index.html
├── style.css
├── app.js
└── service-worker.js
2. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>A Simple PWA</title>
<link rel="stylesheet" href="style.css">
<!-- Manifest for PWA installation -->
<link rel="manifest" href="manifest.json">
</head>
<body>
<h1>Welcome to my simple PWA!</h1>
<button id="btn">Click for alert</button>
<script src="app.js"></script>
</body>
</html>
3. style.css
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
}
4. app.js
// Simple alert on click
document.getElementById('btn').addEventListener('click', () => {
alert('Hi! This is a simple PWA.');
});
// Register the service worker for offline support
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('service-worker.js')
.then(reg => console.log('Service Worker registered:', reg))
.catch(err => console.log('Registration error:', err));
});
}
5. service-worker.js
const cacheName = 'simple-pwa-v1';
const assets = [
'/',
'/index.html',
'/style.css',
'/app.js'
];
// Install and cache
self.addEventListener('install', event => {
event.waitUntil(
caches.open(cacheName)
.then(cache => cache.addAll(assets))
);
});
// Serve resources from cache
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(res => res || fetch(event.request))
);
});
6. manifest.json
{
"name": "A Simple PWA",
"short_name": "Simple PWA",
"start_url": "/index.html",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#2b2b2b",
"icons": [
{
"src": "icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
How it works:
- Open
index.htmlin a modern browser. - Click the "Click for alert" button to test the JS.
- The PWA can be installed on desktop/mobile thanks to
manifest.json. service-worker.jscaches the files so it works offline.