【问题标题】:I'm adding a service worker to WordPress but cannot stop it adding Wordpress files to the cache我正在向 WordPress 添加服务人员,但无法阻止它将 Wordpress 文件添加到缓存
【发布时间】:2017-12-20 15:25:21
【问题描述】:

我正在为我的 WordPress 安装创建一个服务人员。我正在定义要在我的 sw.js 文件中缓存的文件列表,但是在刷新页面时,WordPress 似乎正在加载许多其他文件。

这通常不是问题,但这意味着一些管理文件正在被缓存,这会阻止用户编辑内容。

这是代码。 sw.js 文件位于 Wordpress 的根目录中。名为“test.css”的文件也在根目录中用于测试目的。

任何帮助 - 非常感谢!

-史蒂夫

(function() {
  'use strict';

  var filesToCache = [
      'test.css' 
  ];

  var staticCacheName = 'pages-cache-v1.0.1';

  self.addEventListener('install', function(event) {
    console.log('Attempting to install service worker and cache static assets');
    event.waitUntil(
      caches.open(staticCacheName)
      .then(function(cache) {
        console.log(filesToCache);
        return cache.addAll(filesToCache);
      })
    );
  });

  self.addEventListener('fetch', function(event) {
    //console.log('Fetch event for ', event.request.url);
    event.respondWith(
      caches.match(event.request).then(function(response) {
        if (response) {
          //console.log('Found ', event.request.url, ' in cache');
          return response;
        }
        //console.log('Network request for ', event.request.url);
        return fetch(event.request).then(function(response) {
          return caches.open(staticCacheName).then(function(cache) {
            if (event.request.url.indexOf('test') < 0) {
              cache.put(event.request.url, response.clone());
            }
            return response;
          });
        });
      }).catch(function(error) {
        console.log('Error, ', error);
      })
    );
  });

  self.addEventListener('activate', function(event) {
    //console.log('Activating new service worker...');

    var cacheWhitelist = [staticCacheName];
    event.waitUntil(
      caches.keys().then(function(cacheNames) {
        return Promise.all(
          cacheNames.map(function(cacheName) {
            console.log(cacheNames);
            if (cacheWhitelist.indexOf(cacheName) === -1) {
              return caches.delete(cacheName);
            }
          })
        );
      })
    );
  });

})();

【问题讨论】:

    标签: javascript wordpress caching service-worker progressive-web-apps


    【解决方案1】:

    所以要确定,你的问题是缓存太多了,对吧?

    如果是这种情况,请查看您的代码。如果它在其缓存中没有找到某些东西,它会从网络中获取它 将它放入缓存中。这是代码中唯一的 put 操作。

    你必须解释同样的问题here

    对于刚开始使用 Service Worker 的任何人来说,代码流都是新的,但想想它实际上非常简单。你可以阅读它,它会告诉你它在做什么。查看您在代码中放置的行。看看那条线的周围。发生了什么事?

    希望这会有所帮助:)

    【讨论】:

    • 非常感谢。上面的链接有一些很好的信息。问题与 fetch 函数有关。
    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2021-06-10
    • 2018-02-02
    • 2022-08-02
    相关资源
    最近更新 更多