[PWA] 7. First Cache when installed

本文介绍了如何使用Service Worker缓存资源以支持离线访问。通过在安装阶段创建缓存并预加载必需文件,可以确保应用程序即使在网络不可用的情况下也能正常运行。此外,还讨论了如何在fetch事件中使用缓存来响应请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

If you want your application works offline or lie-wifi. You need to use cache.

 

API:

Create Caches:

caches.open('cache_name').then( (cache) => {
    // create name if not exists yet, return cache if there is a one
})

 

Create single cache:

cache.put(request, response);

cache.addAll([
  '/foo',
  '/bar'
])

 

Get the cache:

cache.match(request)

caches.match(request)

 

When to start cache:

We can do cache in 'installing' service worker, what it will do is fetch everything we need from network and create cache for each of them.

 

self.addEventListener('install', function(event) {
  var urlsToCache = [
    '/',
    'js/main.js',
    'css/main.css',
    'imgs/icon.png',
    'https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff',
    'https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff'
  ];

  event.waitUntil(
    // TODO: open a cache named 'wittr-static-v1'
    // Add cache the urls from urlsToCache
      caches.open('wittr-static-v1')
          .then( (cache) => {
              cache.addAll(urlsToCache)
          })
          .catch( () => {
              console.error("Cannot cache anything");
          })
  );
});

Now we have create the cache, but it is not useful until we use the cache.

 

To use cache, we can do:

self.addEventListener('install', function(event) {
  var urlsToCache = [
    '/',
    'js/main.js',
    'css/main.css',
    'imgs/icon.png',
    'https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff',
    'https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff'
  ];

  event.waitUntil(
    // TODO: open a cache named 'wittr-static-v1'
    // Add cache the urls from urlsToCache
      caches.open('wittr-static-v4')
          .then( (cache) => {
              cache.addAll(urlsToCache)
          })
          .catch( () => {
              console.error("Cannot cache anything");
          })
  );
});

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then((response)=>{
            if(response){
                return response;
            }else{
                return fetch(event.request);
            }
        })
    )
});

So we use 'caches.match' to get all the caches for request.

In the then block, cache is successfully fetched, we check whether there is cache data, if it is, then return the response;

If there is no cache data, then we fetch the data from real-server.

 

But this approach has some problem:

 

After we go offline mode, the pictures are not showing, this is because we only cache when the servcie worker is installed. 

So here is some problem we need to solve:

 

转载于:https://www.cnblogs.com/Answer1215/p/5499313.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值