webpack / webpack-pwa

Example for a super simple PWA with webpack.
https://webpack.github.io/webpack-pwa/page-shell/dashboard.html
810 stars 52 forks source link

Switch to SW-based runtime caching #8

Open jeffposnick opened 7 years ago

jeffposnick commented 7 years ago

Nice job on this repo! It's great to see more architecture examples out there.

One thing to consider doing would be to switch from using localStorage to cache your "API" result to use a runtime caching strategy implemented inside the service worker instead.

You could pull a snippet of code from the offline cookbook (like network, falling back to cache), or you could use a library like sw-toolbox, which has helpers to implement common runtime caching strategies as well as set up routes to match URL patterns to which those strategies should be applied.

If you wanted to follow the current model in which you checked for a cached result from the context of the page prior to making a network request, you could use the Cache Storage API directly (it's exposed to pages via window.caches) instead of window.localStorage.

Relying on a SW-based approach to runtime caching scales much better that localStorage when you're dealing with real-world API requests, and allows you to think about all your offline data (both App Shell + dynamic data) from the context of the Cache Storage API, instead of a mix of the Cache Storage API and localStorage. localStorage also is a synchronous API whose reads and writes block the main thread, so using it for any substantial chunk of data is normally discouraged.

CC: @addyosmani

sokra commented 7 years ago

I actually used localStorage because it's simple. The repo should demonstrate webpack integration and how to store data doesn't infer with webpack. But I would happily accept a PR adding a note with this improvement in a comment.

addyosmani commented 7 years ago

Would you be open to a PR switching to Cache Storage API, @sokra? :)

If not we can PR in a note. I agree with Jeff's take on it being more appropriate for what you're trying to demonstrate and async (though you're right that localStorage is easier to reason about for sure).

I guess it depends on how much webpack-pwa is intended as an experiment vs an idiomatic reference for how SW-based runtime caching should be used. As a data-point, a lot of the Webpack-built PWAs that have shipped this year (Twitter.com, Flipkart, Housing.com, Superbowl etc) opt for Cache Storage API instead of IDB or localStorage for their runtime needs.