Supercharge Caching with Service Workers
This week I learned how to cache API calls using a Service Worker
Most website owners face a challenge of keeping users around for a long time. One solution to this challenge is removing any experience that bores the user, such as long site loading times.
For example, this book-reading website displays Unsplash images on every page of each book. Reading a book means waiting for Unsplash requests every time a reader moves from one page to the other.
As you can notice, this waiting can discourage readers from using the site.
So, we’re going to reduce the time spent on Unsplash requests, using a service worker.
Scenario
We are going to focus on one book and make an assumption that a reader always reads the book from start to finish. This means that they have to access each page of the book.
This book has a list of pre-defined tags that get used when fetching images.
Behind the scene, the website makes two calls to Unsplash for each book page visit. One API call to get image URL using the tag, and another call to retrieve image data.
Service Worker Overview
There is a good article that explains Service workers in detail. You can read more about what the Service Worker can there. For the purpose of this post, we are interested in its network management usage.
Service worker is a programmable network proxy, allowing you to control how network requests from your page, are handled.
Listening for network requests
Once a Service worker is registered, it can listen to all requests made by the site through afetch
event.
For our use case, we are only interested in Unsplash requests.
Each Unsplash request will have a custom header that contains all tags for the book being read. We will then use this header to fetch image URL’s for all tags in a non-blocking manner.
With this service worker in place, we fetch all image URL’s while allowing reader to continue reading the book.
NOTE that this approach of storing image URL’s beforehand can be applied to any network request that has some known relationship with other requests that the user has already made.
For our use case, the tags used to fetch images, are known when the reader starts reading the book.
Conclusion
Service workers can help web developers drastically improve user experience of a website by making use of predictable patterns in the website’s content.