Chapter 4. Intercepting network requests


Chapter 3 looked into using Service Worker caching to dramatically speed up the performance of your website. Instead of the user making a request to the server, the Service Worker intercepts the request and decides to serve it from cache instead. We also briefly touched on how to use Service Workers to transform the requests and responses made by the client using the fetch event.

In this chapter, we’ll dive deeper into the fetch event and you’ll learn more about the many use cases it offers. Service Workers are the key to unlocking the power that lies within your browser. By the end of the chapter, you’ll know how to serve lighter, leaner web pages depending on your user’s browser or preferences. In this section of the book, we’re focusing on the faster part of Progressive Web Apps (PWAs), although it’s important to also ensure that your web apps are resilient and engaging, too.

4.1. The Fetch API

As web developers, we often need the ability to retrieve data from the server in order to update our applications asynchronously. Traditionally, this data is retrieved using JavaScript and the XMLHttpRequest object. Otherwise known as AJAX, this is a developer’s dream because it allows you to update a web page without reloading the page by making HTTP requests in the background. In our sample application, Progressive Times, you use this code to retrieve a list of news articles.

4.2. The fetch event

4.3. Fetch in action

4.4. Summary