gpt4 book ai didi

javascript - 使用 service worker 缓存指向另一个页面的链接

转载 作者:太空狗 更新时间:2023-10-29 16:34:57 25 4
gpt4 key购买 nike

我希望缓存动态链接页面的内容。我有一个注册了 service worker 的简单 index.html,我想将它设置为当你到达此页面时动态缓存链接指向的内容(这个想法是第二个页面不会包含在静态安装事件)。

基本上我正在设计一个页面,该页面将包含指向我希望存储在缓存中的推荐/相关页面的链接。当用户单击指向推荐的相关页面的链接时,我希望它从缓存中加载。

index.html:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<h3>I want to cache</h3>
<a href="page2.html">this link to my second page!</a>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
</script>
</body>
</html>

page2.html:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script2.js"></script>
</head>
<body>
<h1>This is my second page!</h1>
<h3>I want everything from this page to be stored in the cache.</h3>
</body>
</html>

这里是 plunkr:https://plnkr.co/edit/YIAacgkuboyRBkv10hfl?p=catalogue

如何设置我的 fetch 事件以动态缓存第二页的内容,而无需将 page2.html 显式放入我的静态安装事件中?

最佳答案

根据您更新的问题,您可以使用 Client.postMessage() 来完成.

在你的客户端/html/脚本中

<a href="/url/cache-this" class="precache"></a>
<script>
if ('serviceWorker' in navigator) {

// ensure service worker is ready, you can also put this into DOM 'ready' or 'load' event
navigator.serviceWorker.ready.then(function (reg) {

var data = {
action: "precache",
url: $('.precache').attr('href') // if you had more than an url need to be cached, do a loop to collect all data
};
// NOTE: the 'action' is optional, but it is nice to separate your message type, in case you have a lot of communication between DOM and service worker.

// message to SW a stringified string of data.
navigator.serviceWorker.controller.postMessage(JSON.stringify(data));

});
}
</script>

在你的服务 worker 中。

self.addEventListener('message', event => {

if (event.data) {
let data = JSON.parse(event.data); // parse the message back to JSON
if (data.action == "precache") { // check the action
self.toolbox.precache([data.url]); // here you can use sw-toolbox or anything to cache your stuff.
}
}
});

编辑:修正错别字

关于javascript - 使用 service worker 缓存指向另一个页面的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com