Introduction to Service Workers
Service workers in action

Introduction to Service Workers

Have you ever observed that when you are not connected to the Internet, some websites do not show the "no Internet page" instead, we see the normal UI of the website.?

When you are browsing YouTube and your internet disconnects instead of getting that dinosaur game you get the UI of YouTube how does that work??We cannot fetch any JS, CSS, or image files because we are not connected to the internet then how come we are able to see this page?

YouTube page when you are not connected to internet

So internally, YouTube and many other such apps use Service Worker API. The Service Worker API is provided by the browser that can be accessed and controlled using JavaScript. Service workers act as a proxy server (i.e. it intercepts the request) that sit between web applications, browser and the network (when available) and it runs on a separate thread (provided by browser) that does not block your main thread and it does not have access to DOM, local storage, session storage but it has access to push notification and background sync APIs.

Service workers only work in https and not in http to avoid man-in-middle attack.

Let’s see how to register a service worker.?

  • Before actually registering a Service worker we need to check if user’s browser supports service worker or not. To do that you can do the following.?
  • navigator is a Web API provided by browser which internally has access to ServiceWorkerContainer object that provides access to registration, removal, upgrade, and communication with the ServiceWorker

Check if browser supports service worker

To check if a service worker is registered successfully open the browser devtools and head on to the application tab there you would find service workers section as we can see here the source is “sw.js” i.e. is our service worker file name.

Devtools for service workers

The life cycle of a service worker is first it gets installed then it gets activated and finally it is ready to listen to fetch events. SW is event driven worker and to listen to install event you need to add “install” event listener like this.

"Install" service worker event listener

Inside the service worker file, you can use the ServiceWorkerGlobalScope object using self or this.?

The waitUntil method tells browser to hold on and to not finish the install event because we are caching the files that would take some time. If we don’t use waitUntil then the browser might think the install event is done before the files are cached. This could cause issues because the service worker might be activated before it's fully ready

caches represents CacheStorage API provided by browser on which .open method can be used, if the provided cache name is found then it just opens otherwise a new cache table with given name is created.

Cache storage for service workers

The cache object returned inside the callback represents the cache storage which has addAll method it takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache

Once the install event is completed then activate event triggers. The activate event is typically used to perform cleanup activatites i.e. to delete old unnecessary cache from previous versions may no longer be needed.?

For eg: here there are 3 versions of demoApp, we would need the latest one so inside “activate” event we can delete the older version like this:


"activate" service worker event listener

cacheKeyList is an array of all the cache Keys present something like this:

cacheKeyList details

Here we loop over the array and check if the version is not equal to “demoApp-v3” then delete that cache. caches.delete returns a Promise, since we have a loop that returns a Promise we need to use Promise.all. Promise.all combines all these deletion promises into a single promise. This single promise only resolves when every individual deletion promise has resolved, meaning all specified caches have been successfully deleted.

All cache version, before deletion

After the deletion of the old cache version:

After “activate” event, whenever a network request is made by the page that the service worker is responsible for, the fetch event in a service worker is triggered

"fetch" service worker event listener

Service worker’s? fetch event handler intercepts network requests made by the page. It follows a common pattern called cache-then-network, where it first attempts to fetch the resource from the network and, if successful, updates the cache with the fresh response. If the network request fails (e.g., the user is offline), it falls back to serving the cached version of the resource.

If the resource is fetched successfully then callback inside .then method runs if not then .catch callback runs.?

When network request is successful the response (res) is cloned using res.clone(). This is necessary because a Response object can only be consumed once. Cloning allows you to use the response for caching while still returning it to the page.

Then the service worker opens a cache named "demoApp-v3".

It then stores the cloned response (clonedData) in this cache using cache.put(e.request, clonedData). This updates the cache with the latest version of the requested resource.

When network request fails the service worker opens the "demoApp-v3" cache and tries to find a matching request in the cache using cache.match(e.request).

If a matching cached response is found, it is returned to the page, allowing the app to work offline or during network failures.

Github: https://github.com/RyanCrasta/frontend-system-design/tree/service-workers


要查看或添加评论,请登录

Ryan Crasta的更多文章

  • What is useTransition React hook and when to use it?

    What is useTransition React hook and when to use it?

    useTransition is a React hook introduced in React 18. It allows you to handle state updates in a way that lets the UI…

  • How to test your local web app on your phone?

    How to test your local web app on your phone?

    When I was developing a website, I wanted to view it on my mobile and since my development was in progress I didn't…

    2 条评论

社区洞察

其他会员也浏览了