简体   繁体   English

服务工作者缓存进度

[英]service worker cache progress

I am new to java script as well as to PWA. 我是Java脚本和PWA的新手。

I am trying to load all of my contents images/css/audio/video/.html into the cache using cache API which i did successfully using https://developers.google.com and other resources. 我正在尝试使用缓存API将我所有的内容images/css/audio/video/.html加载到缓存中,这是我使用https://developers.google.com和其他资源成功完成的。

My question now is: 我的问题是:
Soon the contents load into the cache the SW(service worker) should tell that all the contents have been loaded. 很快将内容加载到缓存中,SW(服务工作者)应告知所有内容都已加载。 I tried to loop through the static contents which i want to cache, and tried to use alert but it says 我试图遍历要缓存的静态内容,并尝试使用警报,但是它说

Uncaught (in promise) ReferenceError: alert is not defined 未捕获(承诺)ReferenceError:未定义警报

  1. How would SW tell the main page (say index.html) that the contents have been cached without clicking any button or interaction? SW如何在不单击任何按钮或进行任何交互的情况下告诉主页(例如index.html)已缓存内容?

  2. And if there is a possibility of the progress bar which can show the progress of loading the contents into the cache? 进度条是否有可能显示将内容加载到缓存的进度?

  3. as well as telling your actual cache capacity is 'this' and after loading the contents left is 'this' ? 并告诉您实际的缓存容量为“ this”,而加载后的内容为“ this”

You need to add a client.postMessage() to the service worker on the 'activate' event (which occurs after caching is complete), and navigator.serviceWorker.addEventListener('message') Fn to your content page index.html or whatever. 您需要在“激活”事件(在缓存完成后发生)上将client.postMessage()添加到服务工作者,并将navigator.serviceWorker.addEventListener('message')Fn添加到内容页面index.html或其他内容。

Here's code I use: 这是我使用的代码:

// activate with notification TO DOM (!)
global.addEventListener('activate', event => {
  event.waitUntil(async function() {
    await global.clients.claim();
    delay(5000).then(() => {
      data = 'activated';
      console.log('activate msg => dom: ' + data);
      global.clients.matchAll().then(all => all.map(client => client.postMessage(data)));
    });
  }());
});

and on content page script: 并在内容页面脚本上:

navigator.serviceWorker.addEventListener('message', function(event) {
  console.log('sw message: ' + event.data);
  if ( event.data === 'activated' ) {
    somefunctions();
  }
});

Note global.clients.matchAll() broadcasts the message to everything under control of the service worker, which you might not want. 注意global.clients.matchAll()将消息广播到服务工作者控制下的所有对象,而您可能不需要。

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

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