【问题标题】:How to cache json from URL in PWA? [duplicate]如何从 PWA 中的 URL 缓存 json? [复制]
【发布时间】:2021-01-31 14:13:26
【问题描述】:

我已经创建了我的第一个 PWA 页面,但是来自 URL 的数据有问题。在我的页面上,我从 URL 加载 json,这在“在线”时工作得很好,但我不知道如何缓存这些数据并在我的页面作为“离线”工作时加载它。我必须在哪里从 URL 添加这些数据? 这是我加载数据的javascript:

fetch('https://www.json-generator.com/api/json/get/cfTRolENrC?indent=2')
.then(res => res.json())
.then(data => obj = data)
.then(() =>{
  var x = document.getElementById("ad");
console.log(obj);
x.innerHTML = obj[0].name;     
      });

还有我的 sw.js:

self.addEventListener("install", e =>{
    e.waitUntil(
        caches.open("static").then(cache => {
            return cache.addAll(["./","./src/master.css","./images/icon.png"]);
        })
    );
});
self.addEventListener("fetch", e =>{
    e.respondWith(
        caches.match(e.request).then(response => {
            return response || fetch(e.request);
        })
    );
});

【问题讨论】:

  • 我不确定保存字体是否与来自 URL 的 JSON 相同。我必须将 JSON 的 URL 添加到 "cache.addALL("URL") 行中,它将是 enouth?
  • 浏览器不关心您的外部资源是字体、json 文件还是关于粉红色大象的 mp4 电影。
  • 你是对的! :) 感谢您的帮助 :)

标签: javascript html progressive-web-apps service-worker


【解决方案1】:

如果有人有同样的问题。您只需将 JSON URL 添加到静态链接(您在其中提供指向 css、img 等的链接)。它应该是这样的:

self.addEventListener("install", e =>{
    e.waitUntil(
        caches.open("static").then(cache => {
            return cache.addAll(["./","./src/master.css","./images/icon.png",
    "https://www.json-generator.com/api/json/get/cfTRolENrC?indent=2"]);
        })
    );
});
self.addEventListener("fetch", e =>{
    e.respondWith(
        caches.match(e.request).then(response => {
            return response || fetch(e.request);
        })
    );
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2021-12-28
    • 2018-10-10
    • 1970-01-01
    相关资源
    最近更新 更多