简体   繁体   English

使用Service Worker预缓存静态文件

[英]Pre-cache statics files using Service Worker

I am trying to pre-cache some of my static app shell files using service worker. 我正在尝试使用Service Worker预缓存一些静态应用程序外壳文件。 I can't use 'sw-appcache' as I am not using any build system. 我不能使用“ sw-appcache”,因为我没有使用任何构建系统。 However, I tried using 'sw-toolbox' but I am not being able to use it for pre-caching. 但是,我尝试使用“ sw-toolbox”,但无法将其用于预缓存。

Here is what I am doing in my service worker JS: 这是我在服务工作者JS中所做的事情:

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('gdvs-static').then(function(cache) {
        var precache_urls = [
            '/',
            '/?webapp=true',
            '/css/gv.min.css',
            '/js/gv.min.js'
        ];

        return cache.addAll(precache_urls);
    });
  );
});

I've also tried this: 我也尝试过这个:

importScripts('/path/to/sw-toolbox.js');

self.addEventListener('install', function(event) {
   var precache_urls = [
      '/',
      '/?webapp=true',
      '/css/gv.min.css',
      '/js/gv.min.js'
   ];

   toolbox.precache(precache_urls);
});

Here is the URL of my app: https://guidedverses-webapp-staging.herokuapp.com/ Here is the URL of my service worker file: https://guidedverses-webapp-staging.herokuapp.com/gdvs-sw.js 这是我的应用程序的URL: https : //guidedverses-webapp-staging.herokuapp.com/这是我的服务工作者文件的URL: https : //guidedverses-webapp-staging.herokuapp.com/gdvs-sw。 JS

What am I missing? 我想念什么?

Silly me. 傻我 I forgot to add the fetch handler into my service worker. 我忘记将提取处理程序添加到我的服务工作者中。 I thought it works like appchache and automatically returns the cached data when matches with the cache URL. 我认为它的工作原理类似于appchache,并且在与缓存URL匹配时会自动返回缓存的数据。 I underestimated the power of Service Worker. 我低估了服务人员的力量。 Following code did the trick for me. 以下代码对我有用。

this.addEventListener('fetch', function(event) {
  console.log(event.request.url);

  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM