[英]Using the Cache API to cache Web pages without Service Workers
I'm using the Cache API and I'm exploring how much I can do with it without having to use Service Workers. 我正在使用Cache API ,我正在探索我可以用它做多少而不必使用Service Worker。
I have two main use cases: 我有两个主要用例:
For the first use case, I can cache images using the following code: 对于第一个用例,我可以使用以下代码缓存图像:
if('caches' in window) {
caches.open('my-cache').then(function(cache_obj) {
cache_obj.addAll(['/', '/img/first.png', '/img/second.png'])
.then(function() {
console.log('Cached!');
});
});
}
When I take the user offline, then I load the image into the DOM programmatically like so: 当我将用户脱机时,我会以编程方式将图像加载到DOM中,如下所示:
$('body').append('<img src="/img/first.png">');
The image appears on the page as expected. 图像按预期显示在页面上。 If I take out first.png
from the list of cached images, and then repeat this, the image does not appear [because it is not cached]. 如果我从缓存图像列表中取出first.png
,然后重复此操作,则图像不会出现[因为它没有缓存]。 So the Cache API works quite nicely for the first use case. 因此,Cache API对于第一个用例非常有效。
However, I'm wondering if I can do the same thing for the second use case. 但是,我想知道我是否可以为第二个用例做同样的事情。 Can I cache a full HTML page offline, and then have it reload when the user is offline, but without having to setup a service worker? 我可以离线缓存完整的HTML页面,然后在用户离线时重新加载,但无需设置服务工作者吗?
Note : I have a way I can do something very similar using localStorage/sessionStorage to cache the HTML content of the page and then intelligently load it into the current page when the user is offline [using offline.js detection], but I'm looking for a simpler approach using the Cache API. 注意 :我有一种方法可以使用localStorage / sessionStorage来缓存页面的HTML内容,然后在用户离线时智能地将其加载到当前页面[使用offline.js检测],但我是使用Cache API寻找更简单的方法。
This should work for you. 这应该适合你。
You can also read the property navigator.onLine [true/false] 您还可以阅读属性navigator.onLine [true / false]
When the connection is offline , the class is added to the body 当连接脱机时 ,该类将添加到正文中
The Service Worker is not necessary for this task 此任务不需要服务工作者
// We capture the events online - offline
// You can also: if (navigator.onLIne) {... }
window.addEventListener('online', function () {
$('body').toggleClass('offline').append('<img src="/img/first.png">');
});
window.addEventListener('offline', function () {
$('body').toggleClass('offline').append('<img src="/img/second.png">');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.