Search code examples
angularangular5progressive-web-appsangular-pwa

Can Angular 5 Service Worker fetch assets in background


I'm ramping up on progressive web apps using Angular 5. We have a CMS that delivers raw JSON for our application. For content that has images, the JSON contains URLs to the images residing on our server. I'm able to retrieve from our CMS a list of all images (or a filtered list based on conditions).

Does it make sense to retrieve that list of image URLs using a fetch command and have Service Worker cache those assets ahead of time? If so, can Angular 5's implementation of Service Worker be customized to handle a fetch scenario in the background? Or, do I have to create a manual Service Worker to fetch a list of URLs to image assets then cache them?


Solution

  • You can prefetch or lazy load your assets using NGSW as explained here.

    Looks like you are interested in preloading your assets, with the compromise of increased bandwidth and disk space upfront. If managed properly, its definitely a good trade-off to give a faster and smoother user experience in the run time.

    But how you are defining your asset here is little tricky. Your asset lists are pulled dynamically using a JSON file. SW caches your assets when there is an explicit call to them. If your JSON is returning list of images, you can make SW cache that json data and fetching the images in the JSON is not a SW's typical use case and so for NGSW.

    You can still achieve it though in a little different approach. Since your runtime decides what images are valid for a user session/any other conditions, you can have those assets returned as a prerendered html page(think of a ... response) instead of a JSON and inject this HTML chunk in homepage and set visibility to be hidden. This enables SW to naturally cache your dynamically defined/derived assets.

    Update: Explicit cache by URLs, if your don't prefer putting the images in DOM(may be a good idea not to put in DOM when the image list is huge)

    You can explisitly cache some specific URLs using some logic(JSON call and response in your case) by putting a promise in SW as in here and here. sw-test's documentation is here, which has your exact use case of caching image URLs in a JSON response.