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

时间:2017-06-14 13:42:19

标签: javascript php caching progressive-web-apps

我在渐进式网络应用中使用缓存优先策略,我想支持离线浏览。我注意到离线浏览工作正常,但是当我更新网站上的内容时,它仍然显示旧的东西。我不确定我的代码有什么问题,因为我希望它在加载离线之前检查是否有更新内容。我有 manifest.json Service-worker.js Offlinepage.js main.js

以下是我使用的 service-worker.js 代码:

      //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 个答案:

答案 0 :(得分:1)

在链接的src中添加?[VERSION]。

例如:

<script type="text/javascript" src="your_file.js?1500"></script>

每次更新代码时,只需在您的版本中添加一个数字。

实际上这是重复的问题look here for other解决方案。

答案 1 :(得分:1)

我解决了如下所示的问题:即如果用户离线从缓存中获取,则从网络加载

window.close()

答案 2 :(得分:0)

如果要删除所有缓存

caches.keys().then(function(names) {
    for (let name of names)
        caches.delete(name);
});

如果您只知道文件名

caches.delete(name);