【问题标题】:how to cache webp images in service worker?如何在服务工作者中缓存 webp 图像?
【发布时间】:2018-11-01 18:31:37
【问题描述】:

我正在通过以下代码使用 gulp 进行图像缩小和转换为 webp:

gulp.task('minify-images', function(){
  return gulp.src('img/*.+(png|jpg|gif)')
  .pipe(imagemin([
        imagemin.jpegtran({progressive: true}),
        imagemin.gifsicle({interlaced: true}),
        imagemin.optipng({optimizationLevel: 5})
        ]))
  .pipe(webp())
  .pipe(gulp.dest('dist/img'))
});

我在控制台中收到以下错误:

由于控制台错误指向 Service Worker,我是否需要对我的 Service Worker 进行任何更改??

 self.addEventListener('install', function(event) {
   console.log("Service Worker installed");
event.waitUntil(
    caches.open(staticCacheName).then(function(cache) {
      return cache.addAll([
        './',
        './index.html',
        './rt.html',
        './offline.html',   
        './manifest.json',
        // Remove rts.json from cache as  data is  coming from server.
        './css/styles.css',
        './img/1.jpg',
        './img/2.jpg',
        './img/3.jpg',
        './img/4.jpg',
        './img/5.jpg',
        './img/6.jpg',
        './img/7.jpg',
        './img/8.jpg',
        './img/9.jpg',
        './img/10.jpg',
        './img/marker-icon-2x-red.png',
        './img/marker-shadow.png',
        './img/offlinegiphy.gif',
        './img/icons/iconman.png',
        './img/icons/iconman-48x48.png',
        './img/icons/iconman-64x64.png',
        './img/icons/iconman-128x128.png',
        './img/icons/iconman-256x256.png',
        './img/icons/iconman-512x512.png',
        './js/dbhelper.js',
        './js/main.js',
        './js/rt_info.js',
        './register_sw.js',
        './serviceworker.js',
        'https://unpkg.com/leaflet@1.3.1/dist/leaflet.css',
        'https://unpkg.com/leaflet@1.3.1/dist/leaflet.js',
         ]);
    })
  );
   console.log("cache successful");
});

我尝试将 jpg 图像的扩展名更改为 webp,但这也不起作用。 我有几个问题:

  • 为什么我只收到 jpg 图像的错误是因为这些图像是从 API 获取的?
  • 如何在 gulp 缩小和转换后处理服务工作者中缓存的所有图像格式?

请帮忙解决这个问题,如果你能指出一些好的资源,我在这里很困惑,这将是很大的帮助!

编辑 1:

更新 serviceworker.js 代码 `

const staticCacheName = 'rt-rws-v4';
var imgCache = 'rt-img';

var filesToCache=[
        './',
        './index.html',
        './rt.html',
        './offline.html',   
        './manifest.json',
        // Remove rt.json from cache as  data is  coming from server.
        './css/styles.css',
        './js/dbhelper.js',
        './js/main.js',
        './js/rt_info.js',
        './js/idb.js',
        'https://unpkg.com/leaflet@1.3.1/dist/leaflet.css',
        'https://unpkg.com/leaflet@1.3.1/dist/leaflet.js',
         ];
/**
 * This block is invoked when install event is fired
 */
self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function(cache) {
      return cache.addAll(filesToCache);
    })
  );
});
// deletes old cache
self.addEventListener('activate', function(event) {
  // console.log("Service Worker activated");
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheName) {
          return cacheName.startsWith('rt-rws-') &&
                 cacheName != staticCacheName;
        }).map(function(cacheName) {
          return caches.delete(cacheName);
        })
      );
       console.log("Old cache removed");
    })
  );
});

self.addEventListener('fetch', function(event) {
    var requestUrl = new URL(event.request.url);
    // Check if the image type
  if (/\.(jpg|png|gif|webp).*$/.test(requestUrl.pathname)) {
      event.respondWith(cacheImages(event.request));
   return;
}
event.respondWith(
  /*  fetch(returnUrl, {
             mode: 'no-cors'
           }) */
    caches.open(staticCacheName).then(function(cache) {
      return cache.match(event.request).then(function (response) {
        if (response) {
          // console.log("data fetched from cache");
          return response;
        }
        else {
          return fetch(event.request).then(function(networkResponse) {
            // console.log("data fetched from network", event.request.url);
            //cache.put(event.request, networkResponse.clone());
            return networkResponse;
          }).catch(function(error) {
            console.log("Unable to fetch data from network", event.request.url, error);
          });
        }
      });
    }).catch(function(error) {
     // console.log("Something went wrong with Service Worker fetch intercept", error);
     return caches.match('offline.html', error);

    })
  );
});

/**
* @description Adds images to the imgCache
* @param {string} request
* @returns {Response}
*/
function cacheImages(request) {
  var storageUrl = new URL(request.url).pathname;

  return caches.open(imgCache).then(function(cache) {
    return cache.match(storageUrl).then(function(response) {
      if (response) return response;

      return fetch(request).then(function(networkResponse) {
        cache.put(storageUrl, networkResponse.clone());
        return networkResponse;
      });
    });
  });
}

/* // Inspect the accept header for WebP support
  var supportsWebp = false;
  if (event.request.headers.has('accept')){
    supportsWebp = event.request.headers
                                .get('accept')
                                    .includes('webp');
        }
        // If we support WebP
    if (supportsWebp)
    {
        // Clone the request
        var req = event.request.clone();

            // Build the return URL
            var returnUrl = req.url.substr(0, req.url.lastIndexOf(".")) + ".webp";
    //console.log("Service Worker starting fetch"); */

` gulp 任务成功运行并执行任务没有问题

[09:10:50] 使用 gulpfile gulpfile.js

[09:10:50] 开始“缩小图像”...

[09:10:51] gulp-imagemin:缩小 18 张图像(节省 12.84 kB - 6.6%)

[09:10:51] 108 毫秒后完成“缩小图像”

镀铬标题

请求网址:http://localhost:8000/img/6

请求方法:GET 状态码:404 Not Found(来自 ServiceWorker)

远程地址:127.0.0.1:8000

Referrer Policy:no-referrer-when-downgrade

连接:保持活动

内容长度:0

日期:格林威治标准时间 2018 年 11 月 16 日星期五 13:43:03

服务器:ecstatic-3.2.2 显示临时标头

推荐人:http://localhost:8000/

用户代理:Mozilla/5.0(Linux;Android 6.0;Nexus 5 Build/MRA58N)

AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Mobile Safari/537.36

【问题讨论】:

  • /img 目录中是否存在 .jpg 和 .webp 文件?控制台错误中究竟指向服务人员的是什么?我会说最好不要将./register_sw.js./serviceworker.js 与服务人员本身一起缓存,否则您无法更新
  • @AndréKelling 图像优化和转换为 webp 没有问题所有图像都经过优化并转换为 webp 并存储在 dist 文件夹中......我更新了我的服务工作者代码,不再缓存服务工作者文件。 .for 现在删除手动捕获每个图像我正在更新服务工作者代码以通过功能在服务中缓存图像我认为如果问题仍然存在我将在此处更新问题
  • @AndréKelling 更新了服务工作者代码,但问题仍然存在 gulp minify-images 任务正在成功运行,所以我猜问题是服务工作者只添加了标题信息仍然无法理解原因......请帮忙
  • 您说它们存储在dist 文件夹中:您是指img 文件夹吗?你能检查一下缓存中的内容吗?在 chrome 开发工具中 Application > Cache Storage > Name of your cache
  • @AndréKelling 感谢您的帮助我想通了!它现在正在工作。

标签: gulp service-worker bundling-and-minification webp gulp-imagemin


【解决方案1】:

您的压缩 webp 文件存储在 dist/img 中,但应该保存在 img 目录中。

因为它们是从img 请求的。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2022-08-07
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多