캐시된 오디오 및 동영상 제공

일부 브라우저에서 미디어 애셋(즉, <video><audio> 요소의 src 속성에 지정된 URL) 요청을 처리하는 방식에 약간의 차이가 있습니다. Workbox를 구성할 때 특정 단계를 수행하지 않으면 게재 동작이 잘못될 수 있습니다.

문제

오디오 및 동영상 애셋 게재와 관련하여 브라우저가 겪는 복잡한 문제는 이 GitHub 문제 토론에 자세히 설명되어 있습니다. 전체적인 상황은 복잡하지만 핵심은 다음과 같습니다.

  • 핸들러로 사용되는 전략에 workbox-range-requests 모듈을 사용하여 Range 요청 헤더를 따르도록 Workbox에 알려야 합니다.
  • <video> 또는 <audio> 요소는 crossorigin 속성을 사용하여 CORS 모드를 선택해야 합니다.
  • 캐시에서 미디어를 제공하려면 미리 캐시에 명시적으로 추가해야 합니다. 미리 캐싱하거나 cache.add()를 사용하거나, workbox-레시피에서 WarStrategyCache 메서드를 사용하면 됩니다. 재생 중에는 네트워크에서 부분 콘텐츠만 가져오므로 미디어 애셋을 런타임에 스트리밍하는 경우 작동하지 않습니다.

미디어 애셋에 대한 적절한 마크업부터 시작하여 Workbox에서 이러한 요구사항을 충족하는 방법은 다음과 같습니다.

<!-- In your page: -->

<!-- You need to set `crossorigin`, even for same-origin URLs! -->
<video src="movie.mp4" crossorigin="anonymous"></video>
<audio src="song.mp3" crossorigin="anonymous"></audio>

그런 다음 서비스 워커에서 workbox-range-request 플러그인을 사용하여 미디어 애셋을 적절하게 처리합니다.

// sw.js
import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {RangeRequestsPlugin} from 'workbox-range-requests';

// In your service worker:
// It's up to you to either precache, use warmRuntimeCache, or
// explicitly call cache.add() to populate the cache with media assets.
// If you choose to cache media assets up front, do so with care,
// as they can be quite large and exceed storage quotas.
//
// This route will go to the network if there isn't a cache match,
// but it won't populate the cache at runtime because the response for
// the media asset will be a partial 206 response. If there is a cache
// match, then it will properly serve partial responses.
registerRoute(
  ({request}) => {
    const {destination} = request;

    return destination === 'video' || destination === 'audio'
  },
  new CacheFirst({
    cacheName: 'your-cache-name-here',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [200]
      }),
      new RangeRequestsPlugin(),
    ],
  }),
);

이 접근 방식을 사용하면 서비스 워커가 웹사이트의 미디어 애셋을 올바르게 가져오고 캐시하면서 범위 요청 및 미디어 요청과 관련된 기타 잠재적인 문제를 고려할 수 있습니다.