Now.js Framework Documentation

Now.js Framework Documentation

ServiceWorkerManager

TH 15 Dec 2025 08:52

ServiceWorkerManager

ภาพรวม

ServiceWorkerManager คือระบบจัดการ Service Worker ใน Now.js Framework รองรับ caching, offline support และ push notifications

ใช้เมื่อ:

  • ต้องการ offline support
  • ต้องการ cache static assets
  • ต้องการ push notifications
  • ต้องการ background sync

ทำไมต้องใช้:

  • ✅ Automatic caching
  • ✅ Multiple caching strategies
  • ✅ Push notification support
  • ✅ Update management
  • ✅ Precache configuration

การใช้งานพื้นฐาน

Initialization

await ServiceWorkerManager.init({
  enabled: true,
  serviceWorkerPath: '/service-worker.js',
  cacheName: 'my-app-cache-v1',
  debug: true
});

With Push Notifications

await ServiceWorkerManager.init({
  enabled: true,
  push: {
    enabled: true,
    publicKey: 'YOUR_VAPID_PUBLIC_KEY'
  }
});

การตั้งค่า

ServiceWorkerManager.init({
  // Enable/disable
  enabled: true,

  // Service worker file path
  serviceWorkerPath: '/service-worker.js',

  // Scope
  scope: '/',

  // Version for cache busting
  version: '1.0.0',

  // Cache name
  cacheName: 'now-js-cache',

  // Debug logging
  debug: false,

  // Update check interval (ms)
  updateInterval: 24 * 60 * 60 * 1000,  // 24 hours

  // URLs to precache
  precache: [
    '/index.html',
    '/css/styles.css',
    '/js/app.js'
  ],

  // Caching strategies by path
  strategies: {
    '/api/': 'network-first',
    '/images/': 'cache-first',
    '/static/': 'cache-only'
  },

  // Push notification config
  push: {
    enabled: false,
    publicKey: null
  }
});

Caching Strategies

Strategy Description
cache-first ดึงจาก cache ก่อน, fallback to network
network-first ดึงจาก network ก่อน, fallback to cache
stale-while-revalidate ใช้ cache แต่ update ใน background
cache-only ดึงจาก cache เท่านั้น
network-only ดึงจาก network เท่านั้น

API อ้างอิง

ServiceWorkerManager.init(options)

Initialize service worker

Returns: Promise<ServiceWorkerManager>

ServiceWorkerManager.isSupported()

ตรวจสอบ browser support

Returns: boolean

if (ServiceWorkerManager.isSupported()) {
  await ServiceWorkerManager.init({ enabled: true });
}

ServiceWorkerManager.cacheUrls(urls)

Cache URLs ที่กำหนด

Parameter Type Description
urls array Array of URLs

Returns: Promise<boolean>

await ServiceWorkerManager.cacheUrls([
  '/offline.html',
  '/images/logo.png'
]);

ServiceWorkerManager.clearCache()

ล้าง cache ทั้งหมด

Returns: Promise<boolean>

await ServiceWorkerManager.clearCache();

ServiceWorkerManager.update()

Force update service worker

Returns: Promise<boolean>

await ServiceWorkerManager.update();

ServiceWorkerManager.skipWaiting()

Force activate waiting worker

Returns: Promise<boolean>

await ServiceWorkerManager.skipWaiting();

ServiceWorkerManager.isOfflineReady()

ตรวจสอบ offline readiness

Returns: boolean

Push Notifications

Subscribe

const subscription = await ServiceWorkerManager.subscribePush();
// Send subscription to server
await fetch('/api/push/subscribe', {
  method: 'POST',
  body: JSON.stringify(subscription)
});

Unsubscribe

await ServiceWorkerManager.unsubscribePush();

Check Status

if (ServiceWorkerManager.isPushEnabled()) {
  console.log('Push enabled');
}

เหตุการณ์

// Offline ready
EventManager.on('sw:offline-ready', () => {
  console.log('App ready for offline');
});

// Update available
EventManager.on('sw:update-available', () => {
  if (confirm('Update available. Reload?')) {
    window.location.reload();
  }
});

// Cache updated
EventManager.on('sw:cache-updated', () => {
  console.log('Cache refreshed');
});

ตัวอย่างการใช้งานจริง

Progressive Web App

// app.js
if ('serviceWorker' in navigator) {
  await ServiceWorkerManager.init({
    enabled: true,
    cacheName: 'my-pwa-v1',
    precache: [
      '/',
      '/manifest.json',
      '/css/app.css',
      '/js/app.js',
      '/images/icons/icon-192.png'
    ],
    strategies: {
      '/api/': 'network-first',
      '/images/': 'cache-first'
    }
  });
}

With Push Notifications

await ServiceWorkerManager.init({
  enabled: true,
  push: {
    enabled: true,
    publicKey: process.env.VAPID_PUBLIC_KEY
  }
});

// Subscribe button
document.getElementById('notify-btn').onclick = async () => {
  const subscription = await ServiceWorkerManager.subscribePush();

  await fetch('/api/push/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(subscription)
  });

  NotificationManager.success('Notifications enabled!');
};

Update Prompt

EventManager.on('sw:update-available', () => {
  const toast = NotificationManager.show({
    message: 'New version available',
    type: 'info',
    duration: 0,  // Persistent
    actions: [
      {
        label: 'Update',
        callback: () => {
          ServiceWorkerManager.skipWaiting();
          window.location.reload();
        }
      }
    ]
  });
});

Service Worker File

ไฟล์ service-worker.js ที่ต้องสร้าง:

// service-worker.js
const CACHE_NAME = 'my-app-v1';

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll([
        '/',
        '/index.html',
        '/css/styles.css',
        '/js/app.js'
      ]);
    })
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});

ข้อควรระวัง

⚠️ 1. HTTPS Required

// ❌ ไม่ทำงานบน HTTP (ยกเว้น localhost)
// Service Workers require HTTPS

// ✅ ใช้ HTTPS
https://example.com

⚠️ 2. Check Support First

// ❌ ไม่ตรวจสอบ support
ServiceWorkerManager.init({ enabled: true });

// ✅ ตรวจสอบก่อน
if (ServiceWorkerManager.isSupported()) {
  ServiceWorkerManager.init({ enabled: true });
}

เอกสารที่เกี่ยวข้อง