發出要求時,您可以設定 range
標頭,指出在
伺服器只會傳回完整要求的一部分這項功能對於影片檔案等特定檔案非常實用,因為使用者可能會變更播放影片的位置。
本單元的功用
在某些情況下,您可能想放送快取檔案,但瀏覽器已設定 range
標頭。通常會忽略標頭。
這個模組會讀取快取的回應,並傳回指定的資料範圍。
基本用法
如要使用 Workbox 範圍要求,請將外掛程式新增至要檢查範圍要求的策略。
import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {RangeRequestsPlugin} from 'workbox-range-requests';
registerRoute(
({url}) => url.pathname.endsWith('.mp4'),
new CacheFirst({
plugins: [
new RangeRequestsPlugin(),
],
});
);
進階用法
如果想在外掛程式以外的地方使用這個邏輯
可以使用 createPartialResponse()
函式。
import {createPartialResponse} from 'workbox-range-requests';
createPartialResponse(request, cachedResponse);
詳情請參閱參考文件。
類型
RangeRequestsPlugin
範圍要求外掛程式可讓您輕鬆提出含有「Range」(範圍) 的要求標頭至 回應或要求
方法是攔截 cachedResponseWillBeUsed
外掛程式回呼,並傳回快取回應本文的適當子集。
屬性
-
建構函式
void
constructor
函式如下所示:() => {...}
-
returns
-
方法
createPartialResponse()
workbox-range-requests.createPartialResponse(
request: Request,
originalResponse: Response,
)
如果指定 Request
和 Response
物件做為輸入內容,系統會傳回
保證可以獲得新的 Response
。
如果原始 Response
已包含部分內容 (也就是狀態為 206),則系統會假設該內容已符合 Range:
需求,並會原封不動地傳回。
參數
-
申請。
要求
要求,應包含 Range: 標頭。
-
originalResponse
回應
回應。
傳回
-
Promise<Response>
206 Partial Content
回應 (回應主體設為要求Range:
標頭指定的內容片段),或是416 Range Not Satisfiable
回應 (如果無法滿足Range:
標頭的條件)。