Pre-cache Static Resources with Workbox and View a React PWA Offline

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 5 years ago

With our blank workbox based service worker, there is no caching enabled by default. We'll enable caching on all our static assets using workbox's built-in precacheAndRoute method, and this will then allow us to view the PWA in offline mode.

Instructor: [00:00] In the sw.js custom service worker file, let's remove the log statement into our workbox to cache the static resources in our app. This will use the list of files from the pre-cache manifest, which is automatically generated by the inject manifest webpack plug-in and cache those files at the correct route.

[00:23] Let's build and serve that. When we open the app on the console tab, we can see that the pre-cache is responding to all the static assets from our app. We can see what's in the cache by going to the application tab. In the cache storage entry, we can see the assets there.

[00:52] Now that those assets are cached, we can go offline. When we reload, our app still loads. Remember, though, that the items.json API call isn't included in the static assets that are cached. Right now, our app will be stuck in loading forever.

[01:09] If we check the network tab, we can see that that call has failed until we go back online and reload to see the items again.

Marcin
Marcin
~ 5 years ago

Hey Chris, When I go offline and refresh the app, the static assets are indeed served from the service worker's cache, however, the assets that are loaded from index.html (bootstrap etc.) are not loaded and the app looks broken. In your screenshots it looks like those assets are loaded from disk, how so? Would you be able to help with this?

Chris Achard
Chris Achardinstructor
~ 5 years ago

Yes, bootstrap, etc are being served by my browser's cache in this video. In two videos from this one in the course, I talk about that - and add them to the service worker's cache with a route! So check out that video for how to cache those as well. As for forcing your browser to cache them to disk and serve them - I'm not 100% sure if that's possible (or how to do that if it is) which is why it's important to write a new route in the service worker for them if you want them cached as well (see video 7 in this course).

Ernesto Calderon
Ernesto Calderon
~ 5 years ago

New versions of creat-react-app will have the funcrtions skipWaiting and clientsClaim in the core package so instead of workbox.skipWaiting() use workbox.core.skipWaiting()

Chris Achard
Chris Achardinstructor
~ 5 years ago

Ah, thanks for pointing that out Ernesto. I'll have to do an update to the video with the new CRA

Bartosz
Bartosz
~ 5 years ago

Thanks Ernesto!

Andre Souza
Andre Souza
~ 5 years ago

+1 to Ernesto!!!

Markdown supported.
Become a member to join the discussionEnroll Today