如何创建服务工作来存储Progressive WEB APP中的动态内容?

问题描述:

我开发了一个具有静态内容的渐进式Web应用程序,其工作正常,但是当我们动态地从MS SQL数据库中获取数据时,它不起作用。请指导我如何解决此问题,或者需要在Service Worker中为动态数据进行任何更改。如何创建服务工作来存储Progressive WEB APP中的动态内容?

感谢

var version = "1.0::"; 

var offlineResources = [ 
"/", 
"style.css", 
"image/logo.png", 
"image/logo.jpg" 
]; 

self.addEventListener("install", function(event) { 
event.waitUntil(
    caches 
     .open(version + "static") 
     .then(function(cache) { 
      cache.addAll(offlineResources); 
     }) 
); 
}); 

self.addEventListener("activate", function(event) { 
event.waitUntil(
    caches.keys().then(function(keys) { 
     return Promise.all(keys 
      .filter(function (key) { 
       return key.indexOf(version) !== 0; 
      }) 
      .map(function (key) { 
       return caches.delete(key); 
      }) 
     ); 
    }) 
); 
}); 

function isOfflineOrigin(origin) { 
return origin === location.origin || origin.indexOf("netlify") !== -1; 
} 

self.addEventListener("fetch", function(event) { 
var request = event.request; 
var url = new URL(request.url); 

// Only worry about GET requests and certain domains 
if (request.method !== "GET" || !isOfflineOrigin(url.origin)) { 
    return; 
} 

// For HTML try the network first, fall back to the cache, and then 
// finally the offline page 
if (request.headers.get("Accept").indexOf("text/html") !== -1) { 
    event.respondWith(
     fetch(request) 
      .then(function(response) { 
       var copy = response.clone(); 
       caches.open(version + "pages") 
        .then(function(cache) { 
         cache.put(request, copy); 
        }); 
       return response; 
      }) 
      .catch(function() { 
       return caches.match(request) 
        .then(function(response) { 
         return response || caches.match("/offline/"); 
        }); 
      }) 
    ); 
    return; 
} 

// For non-HTML requests look in the cache first, and fall back to 
// the network 
event.respondWith(
    caches.match(request) 
     .then(function(response) { 
      return response || fetch(request); 
     }) 
); 
}); 
+0

您认为您对动态内容的请求所采用的路径是什么? – Salva

我可以找出你只缓存静态资源。 What about the dynamic content like the responses from a remote API or service? 您必须为所有动态需求实现运行时缓存。

sw-toolbox来得方便,它可以灵活地实现处理远程或动态资源的运行时缓存的请求处理程序。

+0

非常感谢你连锁。如果有人能够分享这个例子,这将会非常有帮助。我想要做缓存动态图像。图像将随着新的文章而改变。 – umang