douan3182 2017-06-14 13:42
浏览 79
已采纳

当Cache-First策略中的内容发生更改时,网站不会更新

I am using Cache-first strategy in my progressive web app that i want to support offline browsing. I have noted that offline browsing is working fine but when i update content on the website,it still showing the old stuff.I am not sure what is wrong with my code because i want it to check if there is an update before loading the offline content. I have manifest.json, Service-worker.js, Offlinepage.js and main.js.

Here is my service-worker.js code that i have used:

      //service worker configuration
      'use strict';

      const
        version = '1.0.0',
        CACHE = version + '::PWA',
        offlineURL = '/offline/',
        installFilesEssential = [
         '/',
          '/manifest.json',
          '/theme/pizza/css/style.css',
           '/theme/pizza/css/font-awesome/font-awesome.css',
          '/theme/pizza/javascript/script.js',
          '/theme/pizza/javascript/offlinepage.js',
          '/theme/pizza/logo.png',
          '/theme/pizza/icon.png'
        ].concat(offlineURL),
        installFilesDesirable = [
          '/favicon.ico',
         '/theme/pizza/logo.png',
          '/theme/pizza/icon.png'
        ];

      // install static assets
      function installStaticFiles() {

        return caches.open(CACHE)
          .then(cache => {

            // cache desirable files
            cache.addAll(installFilesDesirable);

            // cache essential files
            return cache.addAll(installFilesEssential);

          });

      }
      // clear old caches
      function clearOldCaches() {

        return caches.keys()
          .then(keylist => {

            return Promise.all(
              keylist
                .filter(key => key !== CACHE)
                .map(key => caches.delete(key))
            );

          });

      }

      // application installation
      self.addEventListener('install', event => {

        console.log('service worker: install');

        // cache core files
        event.waitUntil(
          installStaticFiles()
          .then(() => self.skipWaiting())
        );

      });

      // application activated
      self.addEventListener('activate', event => {

        console.log('service worker: activate');

        // delete old caches
        event.waitUntil(
          clearOldCaches()
          .then(() => self.clients.claim())
        );

      });

      // is image URL?
      let iExt = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'].map(f => '.' + f);
      function isImage(url) {

        return iExt.reduce((ret, ext) => ret || url.endsWith(ext), false);

      }


      // return offline asset
      function offlineAsset(url) {

        if (isImage(url)) {

          // return image
          return new Response(
            '<svg role="img" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg"><title>offline</title><path d="M0 0h400v300H0z" fill="#eee" /><text x="200" y="150" text-anchor="middle" dominant-baseline="middle" font-family="sans-serif" font-size="50" fill="#ccc">offline</text></svg>',
            { headers: {
              'Content-Type': 'image/svg+xml',
              'Cache-Control': 'no-store'
            }}
          );

        }
        else {

          // return page
          return caches.match(offlineURL);

        }

      }

      // application fetch network data
      self.addEventListener('fetch', event => {

        // abandon non-GET requests
        if (event.request.method !== 'GET') return;

        let url = event.request.url;

        event.respondWith(

          caches.open(CACHE)
            .then(cache => {

              return cache.match(event.request)
                .then(response => {

                  if (response) {
                    // return cached file
                    console.log('cache fetch: ' + url);
                    return response;
                  }

                  // make network request
                  return fetch(event.request)
                    .then(newreq => {

                      console.log('network fetch: ' + url);
                      if (newreq.ok) cache.put(event.request, newreq.clone());
                      return newreq;

                    })
                    // app is offline
                    .catch(() => offlineAsset(url));

                });

            })

        );

      });
  • 写回答

3条回答 默认 最新

  • dqvs45976 2017-06-16 01:42
    关注

    I solved the issue as shown below: i.e if user is offline fetch from cache else load from network

    // application fetch network data
    self.addEventListener('fetch', event => {
    
      // abandon non-GET requests
      if (event.request.method !== 'GET') return;
    
      let url = event.request.url;
    
      event.respondWith(
    
        caches.open(CACHE)
          .then(cache => {
    
            return cache.match(event.request)
              .then(response => {
    
                if (response && !navigator.onLine) {
                    // return cached file
                    console.log('cache fetch: ' + url);
                    return response;
                  }
                   // make network request
                  return fetch(event.request)
                    .then(newreq => {
    
                      console.log('network fetch: ' + url);
                      if (newreq.ok) cache.put(event.request, newreq.clone());
                      return newreq;
    
                    })
                    // app is offline
                    .catch(() => offlineAsset(url));
    
    
    
              });
    
          })
    
      );
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条