Progressive Web Apps (PWA) — Web Fundamentals

Progressive Web Apps (PWA) adalah website yang bisa berperilaku seperti aplikasi native — bisa di-install, bekerja offline, dan mengirim push notification. Tiga

Progressive Web Apps (PWA) adalah website yang bisa berperilaku seperti aplikasi native — bisa di-install, bekerja offline, dan mengirim push notification.

Tiga pilar PWA:

1. Web App Manifest (manifest.json) File JSON yang memberitahu browser bahwa website kamu bisa di-install:

{
  "name": "BelajarWeb.dev",
  "short_name": "BelajarWeb",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#4f46e5",
  "icons": [
    { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
  ]
}
<link rel="manifest" href="/manifest.json">

2. Service Worker Script yang berjalan di background, terpisah dari halaman web. Ia bisa intercept network requests, cache resources, dan bekerja saat offline.

// sw.js — Service Worker
const CACHE = "v1";
const ASSETS = ["/", "/index.html", "/style.css", "/app.js"];

// Install: cache semua assets
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE).then((cache) => cache.addAll(ASSETS))
  );
});

// Fetch: serve from cache, fallback to network
self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});

// Registrasi di main app:
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("/sw.js");
}

3. HTTPS PWA wajib dijalankan via HTTPS (kecuali localhost untuk development).

Caching strategies:

Strategy Cocok Untuk
Cache First Assets statis (CSS, JS, gambar)
Network First API data yang sering berubah
Stale While Revalidate Data yang boleh sedikit outdated
Cache Only Assets yang tidak pernah berubah
Network Only Data yang harus selalu fresh

Push Notifications:

// Minta izin
const permission = await Notification.requestPermission();

if (permission === "granted") {
  // Subscribe ke push service
  const subscription = await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: vapidPublicKey
  });

  // Kirim subscription ke server kamu
  await fetch("/api/push/subscribe", {
    method: "POST",
    body: JSON.stringify(subscription)
  });
}

Tools:

PWA adalah masa depan web — satu codebase untuk semua platform.