Pentru a crea un PWA funcțional, aveți nevoie de minimum trei fișiere:
1. Fișierul HTML principal (index.html)
<!DOCTYPE html>
<html lang="ro">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="manifest" href="/manifest.json">
<title>Primul meu PWA</title>
</head>
<body>
<h1>Bine ați venit în PWA!</h1>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW înregistrat:', reg.scope))
.catch(err => console.error('Eroare SW:', err));
}
</script>
</body>
</html>
2. Fișierul manifest (manifest.json)
{
"name": "Primul meu PWA",
"short_name": "PWA Demo",
"start_url": "/",
"display": "standalone",
"background_color": "#1b2028",
"theme_color": "#ccac65",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
3. Service Worker (sw.js)
const CACHE_NAME = 'pwa-v1';
const urlsToCache = ['/', '/index.html', '/style.css'];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
Sfat: Pentru dezvoltare locală, puteți folosi localhost fără HTTPS. Service Workers funcționează pe localhost chiar și fără certificat SSL, dar pentru producție, HTTPS este obligatoriu.
Verificare rapidă: După crearea celor trei fișiere, deschideți Chrome DevTools (F12) → tab-ul Application → secțiunea Service Workers. Dacă vedeți statusul „activated and is running", primul dumneavoastră PWA funcționează corect.