ApiaryActive
Try: pause · settings · learn · wipe
← Community / Reading Room
BS
browser-apis · 3 min read

browser service worker basics

=====================================

=====================================

Imagine a world where your web application can function even when the user is offline or has a slow internet connection. A service worker is a script that runs in the background, allowing you to cache resources and handle network requests efficiently.

In this article, we will explore the basics of browser service workers, including installation, activation, fetch interception, and caching strategies. By the end of this tutorial, you'll be able to create your own service worker scripts and enhance the user experience of your web application.

Installing a Service Worker

The first step in creating a service worker is to install it. You can do this by registering the script with the navigator.serviceWorker API. Here's an example:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then(registration => console.log('Service worker registered:', registration))
      .catch(error => console.error('Error registering service worker:', error));
  });
}

In this example, we're checking if the serviceWorker property exists in the navigator object. If it does, we add an event listener to the load event of the window and register the /sw.js script as a service worker.

Activating a Service Worker

Once installed, the service worker will be activated when the user navigates to a page that has been registered for service worker control. You can check if the service worker is active using the following code:

self.addEventListener('activate', () => {
  console.log('Service worker activated');
});

In this example, we're listening for the activate event and logging a message to the console when it's triggered.

Fetch Interception

One of the main features of service workers is fetch interception. This allows you to modify or cancel network requests made by your web application. Here's an example:

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

In this example, we're listening for the fetch event and checking if a cached version of the requested resource exists. If it does, we return the cached response; otherwise, we attempt to fetch the resource from the network.

Cache-First vs Network-First Strategies

When implementing fetch interception, you'll need to decide between a cache-first or network-first strategy. A cache-first strategy prioritizes cached resources over network requests, while a network-first strategy does the opposite. Here's an example of each:

// Cache-first strategy
self.addEventListener('fetch', event => {
  caches.match(event.request)
    .then(response => response || fetch(event.request).catch(() => Promise.resolve()))
});

// Network-first strategy
self.addEventListener('fetch', event => {
  fetch(event.request)
    .then(response => caches.open('my-cache').then(cache => cache.put(event.request, response)))
});

In the first example, we're checking for a cached version of the requested resource before attempting to fetch it from the network. In the second example, we're prioritizing network requests and caching the response in a cache named "my-cache".

When Not to Use Service Workers

While service workers can greatly enhance the user experience of your web application, there are some cases where you may not want to use them:

  • Simple applications: If your application doesn't require complex caching or fetch interception logic, you may not need a service worker.
  • Legacy browsers: Unfortunately, some older browsers don't support service workers. You'll need to consider this when deciding whether to implement service workers in your application.

Related Apiary Lessons

If you're interested in learning more about browser APIs and web development best practices, check out the following related lessons:

And that's it! With this article, you should now have a solid understanding of the basics of browser service workers. Remember to experiment with different caching strategies and fetch interception techniques to find what works best for your application.

Bee-utiful code, everyone!

Frequently asked
What is browser service worker basics about?
=====================================
What should you know about installing a Service Worker?
The first step in creating a service worker is to install it. You can do this by registering the script with the navigator.serviceWorker API. Here's an example:
What should you know about activating a Service Worker?
Once installed, the service worker will be activated when the user navigates to a page that has been registered for service worker control. You can check if the service worker is active using the following code:
What should you know about fetch Interception?
One of the main features of service workers is fetch interception. This allows you to modify or cancel network requests made by your web application. Here's an example:
What should you know about cache-First vs Network-First Strategies?
When implementing fetch interception, you'll need to decide between a cache-first or network-first strategy. A cache-first strategy prioritizes cached resources over network requests, while a network-first strategy does the opposite. Here's an example of each:
References & sources
  1. Apiary Reading RoomOpen, cited knowledge base — funded to keep bee & practical research free.
From the Apiary Reading Room. Opinion & editorial — not financial advice. We don't overclaim.
More from the Reading Room