0
0
JavascriptHow-ToBeginner · 4 min read

How to Use Service Workers in JavaScript: Simple Guide

To use service workers in JavaScript, first register the service worker script with navigator.serviceWorker.register(). Then, inside the service worker file, listen for events like install and fetch to control caching and network requests.
📐

Syntax

Using service workers involves two main parts: registering the service worker in your main JavaScript file, and writing the service worker script itself.

  • Registration: Use navigator.serviceWorker.register('service-worker.js') to start the service worker.
  • Service Worker Script: This script listens for lifecycle events like install and fetch to manage caching and network requests.
javascript
// Registering a service worker in your main JS file
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('service-worker.js')
    .then(registration => {
      console.log('Service Worker registered with scope:', registration.scope);
    })
    .catch(error => {
      console.error('Service Worker registration failed:', error);
    });
}

// Inside service-worker.js
self.addEventListener('install', event => {
  console.log('Service Worker installing...');
  // Perform install steps like caching
});

self.addEventListener('fetch', event => {
  console.log('Fetching:', event.request.url);
  // Respond with cached resources or fetch from network
});
Output
Service Worker registered with scope: http://yourdomain/ Service Worker installing... Fetching: http://yourdomain/index.html
💻

Example

This example shows how to register a service worker and cache a file during installation. It then serves the cached file when offline.

javascript
// main.js
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('sw.js')
    .then(reg => console.log('Service Worker registered:', reg.scope))
    .catch(err => console.error('Registration failed:', err));
}

// sw.js
const CACHE_NAME = 'my-cache-v1';
const urlsToCache = ['index.html', 'styles.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))
  );
});
Output
Service Worker registered: http://yourdomain/ // When offline, requests for cached files are served from cache
⚠️

Common Pitfalls

  • Not checking if navigator.serviceWorker exists before registering causes errors in unsupported browsers.
  • Forgetting to call event.waitUntil() in install event can cause the service worker to install prematurely.
  • Not handling fetch events properly can lead to failed network requests or stale content.
  • Service workers only work on secure origins (HTTPS) or localhost for testing.
javascript
// Wrong: No feature check
navigator.serviceWorker.register('sw.js'); // May throw error if unsupported

// Right: Check support first
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('sw.js');
}

// Wrong: Missing event.waitUntil in install
self.addEventListener('install', event => {
  caches.open('cache'); // This may not complete before install finishes
});

// Right: Use event.waitUntil
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('cache')
  );
});
📊

Quick Reference

Remember these key points when working with service workers:

  • Register service worker with navigator.serviceWorker.register().
  • Use install event to cache files.
  • Use fetch event to serve cached content or fetch from network.
  • Always check for browser support.
  • Service workers require HTTPS or localhost.

Key Takeaways

Always check if service workers are supported before registering.
Use the install event to cache important files for offline use.
Handle fetch events to serve cached content or fallback to network.
Service workers only work on HTTPS or localhost for security reasons.
Use event.waitUntil() to ensure async tasks complete during install.