Intro to Client side Caching with Service-Worker

Saravanan Ramupillai
JS 360

--

Service worker is a yet another javascript program that runs in the browser background. It has no connection with normal javascript programs that is loaded by our webpage. This behaviour provides a possibility for executing long running task like background sync, push notification and support for offline apps with effective caching support.

Service worker act as http proxy for browser, that allows us intercept the request that send to server. This allows us to do something really interesting.

A service worker life can be in any one of the following state.

Image from Google official docs

Writing a service-worker is as simple as create one javascript file. Browser will execute this script in service worker environment. Here is simple service worker that caches the all gif image resource.

What it does :

  1. Intercept the http request ( line — 7 ) browser sends to server to fetching the image.
  2. Checks whether this image is already cached ( line — 16 )
  3. If not send a request to fetch that image and and save it in cache ( line 28–40 )
  4. Return the request result back to browser (line — 45).

We wrote the our first service worker, but still we did not register it with browser. To register the service worker, we going to use serviceworker api available in navigator.

Index.js

At line-3 we are registering our service worker with browser. Register method returns a promise, on successful registration it will be resolved with registration information. On failure it will raise an error.

Add index.js in html file and run using some local http-server.

index.html

We are loading two gif images into document that will be cached by our service worker when we visit first time. On reloading the page, these images will be served from service worker cache instead of from server.

Open browser network panel and you can see, (Request No-2. Po.gif) gifs are served from service worker.

This is the simple way to cache your website asset and reduce the site load time. There is lot more best practices to cover, we will cover it in upcoming posts.

Source from official docs.

--

--