1. Welcome
In this lab, you'll take an existing web application add a streaming route response to improve performance. This is the seventh in a series of companion codelabs for the Progressive Web App workshop. The previous codelab was Empowering your PWA. There is one more codelab in this series.
What you'll learn
- Add a streaming response to a service worker
What you should know
- JavaScript
What you will need
- A browser that supports Service Workers and Streams
2. Get Set Up
Start by either cloning or downloading the starter code needed to complete this codelab:
If you clone the repo, make sure you're on the pwa06--service-worker-includes
branch. The zip file contains the code for that branch, too.
This codebase requires Node.js 14 or higher. Once you have the code available, run npm ci
from the command line in the code's folder in order to install all of the dependencies you'll need. Then, run npm start
to start the development server for the codelab.
The source code's README.md
file provides an explanation for all distributed files. In addition, the following are the key existing files you'll be working with throughout this codelab:
Key Files
js/preview.js
- Preview page's JavaScript fileservice-worker.js
- PWA's service worker file
3. Streaming Preview
The preview page can be broken down into three clear pieces: the head, the compiled body, and the foot. Currently, the compiled body is being rendered client-side, but there's no reason for it to be. Let's move it to the Service Worker.
In order to compile the body, there is an async content lookup. Because async work in a navigation response is expensive, it''s a great opportunity to stream the known content to the browser first.
To do so, first clear the content in js/preview.js
to ensure that it's no longer doing the compiling. Then, in service-worker.js
, do the following:
- Import the named export
strategy
fromworkbox-streams
asstreamsStrategy
- Import the named export
openDB
and fromidb
and import the named exportmarked
frommarked
- Before the route registration for navigations, add a new route registration
- It should check that the URL's
pathname
is/preview
- It should use a streaming strategy that
- Respond with the content of
preview/index.html
through the content are of themain
tag - Respond with a function that opens the
settings-store
IndexedDB, gets the content from thesettings
object store, and returns the markdown rendered version of that content. - Respond with the closing
main
,body
, andhtml
tags.
- Respond with the content of
- It should check that the URL's
With the streaming response in place, go back and open up the site preview in your browser. You should see that the page content is now being rendered directly from the service worker, no client-side code required!
4. Congratulations!
You've learned how to take your web app offline using service workers and the cache storage API.
The next codelab in the series is Working with Workers