Javascript 缓存优先策略中的内容更改时网站不更新

Javascript 缓存优先策略中的内容更改时网站不更新,javascript,php,caching,progressive-web-apps,Javascript,Php,Caching,Progressive Web Apps,我在我的渐进式web应用程序中使用缓存优先策略,以支持脱机浏览。我注意到离线浏览工作正常,但当我更新网站上的内容时,它仍然显示旧内容。我不确定我的代码有什么问题,因为我希望它在加载离线内容之前检查是否有更新。我有manifest.json、Service worker.js、Offlinepage.js和main.js 以下是我使用的服务工作者.js代码: //service worker configuration 'use strict'; const

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

以下是我使用的服务工作者.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));

                });

            })

        );

      });
//服务工作者配置
"严格使用",;
常数
版本='1.0.0',
缓存=版本+'::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(离线URL),
安装文件数量=[
“/favicon.ico”,
“/theme/pizza/logo.png”,
“/theme/pizza/icon.png”
];
//安装静态资产
函数installStaticFiles(){
返回缓存。打开(缓存)
。然后(缓存=>{
//缓存需要的文件
cache.addAll(installfiles);
//缓存基本文件
返回cache.addAll(installfilesential);
});
}
//清除旧物
函数clearOldCaches(){
返回缓存
。然后(keylist=>{
回报你的承诺(
钥匙表
.filter(键=>键!==缓存)
.map(key=>caches.delete(key))
);
});
}
//应用程序安装
self.addEventListener('install',事件=>{
日志('service worker:install');
//缓存核心文件
event.waitill(
installStaticFiles()
.然后(()=>self.skipWaiting())
);
});
//应用程序激活
self.addEventListener('activate',event=>{
console.log('service worker:activate');
//删除旧缓存
event.waitill(
clearOldCaches()
.然后(()=>self.clients.claim())
);
});
//是图像URL吗?
让iExt=['png','jpg','jpeg','gif','webp','bmp'].map(f=>'.+f);
函数isImage(url){
返回iExt.reduce((ret,ext)=>ret | | url.endsWith(ext),false);
}
//归还离线资产
函数offlineAsset(url){
如果(isImage(url)){
//返回图像
返回新的响应(
“离线离线”,
{标题:{
“内容类型”:“图像/svg+xml”,
“缓存控制”:“无存储”
}}
);
}
否则{
//返回页
返回caches.match(脱机URL);
}
}
//应用程序获取网络数据
self.addEventListener('fetch',event=>{
//放弃非GET请求
if(event.request.method!=“GET”)返回;
让url=event.request.url;
事件响应(
缓存。打开(缓存)
。然后(缓存=>{
返回cache.match(event.request)
。然后(响应=>{
如果(答复){
//返回缓存文件
log('cache-fetch:'+url);
返回响应;
}
//发出网络请求
返回获取(event.request)
.然后(newreq=>{
log('networkfetch:'+url);
if(newreq.ok)cache.put(event.request,newreq.clone());
返回newreq;
})
//应用程序处于脱机状态
.catch(()=>offlineAsset(url));
});
})
);
});

在链接的src中添加?[版本]

例如:

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

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


实际上,这是重复的问题解决方案。

我解决了如下问题:即,如果用户脱机,则从缓存获取,否则从网络加载

// 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));



          });

      })

  );

});

如果要删除所有缓存

caches.keys().then(function(names) {
    for (let name of names)
        caches.delete(name);
});
如果你知道文件名

caches.delete(name);

这个没有效果。仅当我删除旧缓存并重新加载页面时,更新的内容才会更新。在不首先清除缓存的情况下重新加载可确保显示旧内容。也许这是服务人员的弱点。虽然我可能错了。你在其他浏览器中测试过吗?是的,我有。如果我把它附加到CSS链接上,它能工作吗?是的,它能工作。我不明白为什么它不能工作。当链接更改时,即使您添加或删除了浏览器中新的字母,也要重新下载。即使用户联机,您也可以从缓存中提供页面。我只将解决方案应用于离线用户。因此,当他们再次联机时,我们可以清除缓存并提供有效页面。@DmitriyNesteryuk您是对的。我真的在寻找一种方法来确保所有用户获得最新的数据,并确保页面加载速度更快