progressive-web-appsservice-workeroffline-caching

Service Worker caching/playback of videos: what is the most compatible approach?


Im currently working on a small PWA which should also include several local video files offline. (Using a precache szenario) I've already noticed that the caching of such files is not straightforward, especially for iOS devices because of the limited range request. I've already tried this solution proposed at at similar question: PWA - cached video will not play in Mobile Safari (11.4) But for me that didn't work either.

They only working solutions I found online used some form of blob handling in combination with either the File API or Indexed DB Storage https://simpl.info/video/offline/

Is it possible to cache an entire HTML5 video using the Service Worker API for offline use?

As this where rather old posts I was wondering, which strategy would be appropriate concerning current apis (but also targeting older iOs Devices)

Thank you in advance.


Solution

  • If you're willing to go all-in on Workbox, the information at "Serve cached audio and video" should be accurate across multiple browsers and platforms.

    If you'd rather handle caching yourself but just want some help creating an HTTP 206 partial response, given an incoming Request and a Response object that you've read from a cache, you can just use the createPartialResponse() method from workbox-range-requests, without using the rest of Workbox:

    import {createPartialResponse} from 'workbox-range-requests';
    
    self.addEventListener('fetch', (event) => {
      const {request} = event;
      if (request.headers.has('range')) {
        event.respondWith((async () => {
          const cache = await caches.open('media');
          const fullResponse = await cache.match(request);
          if (fullResponse) {
            return createPartialResponse(request, fullResponse);
          }
          // If there's a cache miss, fall back to the network.
          return fetch(request);
        })());
      }
    });
    

    You can also take a look at the createPartialResponse() method's source if you want to implement that yourself.