簡體   English   中英

使用Workbox啟動運行時服務工作程序緩存

[英]Priming a runtime service worker cache using Workbox

如何在WorkboxSW中使用以下代碼為所有按緩存的URL注冊路由。 此每個緩存的URL包括也將發送到服務器的Ajax!

$.ajax({
   url : '/MyAPI/Records',
   type : 'GET',
   dataType:'json',
   success : function(data) {              
     alert('Records: '+data);

     //build urls array to get all records details  
     var urls = [];
     urls.push('/MyAPI/Records')
     $(data).each(function (index) {
        urls.push('/MyAPI/Records/' + data[index].id + '/data') 
      });

     //add all urls to cache
     var requests = urls.map(url => new Request(url));
     caches.open('my-cache').then(cache => {
     return cache.addAll(requests).then(() => {
        // At this point, `cache` will be populated with `Response` objects,
        // and `requests` contains the `Request` objects that were used.
     }).catch(error => console.error(`Oops! ${error}`));
  });
},
error : function(request,error)
{
    alert("Request: "+JSON.stringify(request));
}
});

Workbox的預緩存依賴於在構建時訪問代表資源的本地文件。 這樣,它就可以生成其管理的每個資源的哈希(基於本地文件的內容),然后只要本地文件發生更改,就可使該緩存的資源保持最新。

您的建議聽起來更像是Workbox支持通過運行時緩存處理某些路由。 您可以通過以下方式進行配置:

// Replace with your actual API endpoint.
const API_URL = 'https://my-api-server.com/api/restEndpoint';

// Use whichever strategy you'd prefer: networkFirst, staleWhileRevalidate, etc.
const apiCallHandler = workboxSW.strategies.networkFirst({
  cacheName: 'my-api'
});

workboxSW.registerRoute(
  API_URL,
  apiCallHandler
);

發出第一個請求后,這將導致來自https://my-api-server.com響應在運行時被添加到名為my-api的緩存中。 (在這種特殊情況下,使用networkFirst策略,僅當網絡不可用時才使用那些緩存的響應。)

如果您對運行時緩存以“ cold”開頭不滿意,並且感覺需要對其進行初始化,則可以通過在Workbox代碼旁邊編寫自己的install事件處理程序來做到這一點:

// Your existing WorkboxSW code goes here.

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('my-api')
      .then(cache => cache.add(API_URL))
  );
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM